SlideShare a Scribd company logo
Vectors
 Vector implements a DYNAMIC ARRAY.
 Vectors can hold objects of any type and any number.
 Vector class is contained in java.util package
 Vector is different from ARRAY in two ways:-
1. Vector is synchronized.
2. It contains many legacy methods that are not part of the collection
framework. 1. Enumeration.
2. Iterator
Declaring VECTORS
Vector list = new Vector();
Vector list = new Vector(int size);
Vector list = new Vector(int size, int incr);
Creates a default vector, which has
an initial size 10.
Creates a vector, whose initial
capacity is specified by size.
Creates a vector, whose initial capacity is specified
by size and whose increment is specified by incr.
Vectors (Contd….)
 A vector can be declared without specifying any size explicitly.
 A vector without size can accommodate an unknown number of
items.
 Even when size is specified, this can be overlooked and a different
number of items may be put into the vector
In contrast, An ARRAY must have its size
specified.
Sr.no Method Discription
1
void add(int index, Object
element)
Inserts the specified element at the specified position in this
Vector.
2 boolean add(Object o) Appends the specified element to the end of this Vector.
3 boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end
of this Vector, in the order that they are returned by the specified
Collection's Iterator.
4 void addElement(Object obj)
Adds the specified component to the end of this vector, increasing
its size by one.
5 int capacity() Returns the current capacity of this vector.
6 void clear() Removes all of the elements from this Vector.
7
void copyInto(Object[]
anArray)
Copies the components of this vector into the specified array.
8 Object elementAt(int index) Returns the component at the specified index.
9 boolean equals(Object o) Compares the specified Object with this Vector for equality.
10 Object firstElement() Returns the first component (the item at index 0) of this vector.
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
Vector v = new Vector(3, 2); // initial size is 3, increment is 2
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +v.capacity());
v.addElement(new Integer(2));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " +v.lastElement());
}
}
Example
Wrapper Classes
 Most of the objects collection store objects and not
primitive types.
 Primitive types can be used as object when required.
 As they are objects, they can be stored in any of the
collection and pass this collection as parameters to
the methods.
Wrapper Class
 Wrapper classes are classes that allow primitive types to
be accessed as objects.
 Wrapper class is wrapper around a primitive data type
because they "wrap" the primitive data type into an object
of that class.
What is Wrapper Class?
 Each of Java's eight primitive data types has a class dedicated to it.
 They are one per primitive type.
 Wrapper classes make the primitive type data to act as objects.
Simple Type Wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
short Short
byte Byte
Difference b/w Primitive Data Type and
Object of a Wrapper Class
 The following two statements illustrate the difference between a
primitive data type and an object of a wrapper class:
int x = 25;
Integer y = new Integer(33);
Clearly x and y differ by more than their values:
• x is a variable that holds a value;
• y is an object variable that holds a reference to an object.
So, the following statement using x and y as declared above is not allowed:
int z = x + y; // wrong!
 The data field in an Integer object is only accessible using
the methods of the Integer class.
 One such method is intValue() method which returns an int
equal to the value of the object, effectively "unwrapping" the
 Integer object:
int z = x + y.intValue(); // OK!
Boxing and Unboxing
 The wrapping is done by the compiler.
 if we use a primitive where an object is expected, the compiler boxes the primitive in its
wrapper class.
 Similarly, if we use a number object when a primitive is expected, the compiler un-
boxes the object.
 Example of boxing and unboxing:
Integer x, y; x = 12; y = 15; System.out.println(x+y);
 When x and y are assigned integer values, the compiler boxes the integers
because x and y are integer objects.
 In the println() statement, x and y are unboxed so that they can be added as
integers.
Integer Class
 Constructors:
 Integer(i) : constructs an Integer object equivalent to the integer i
 Integer(s) : constructs an Integer object equivalent to the string s
 Integer Class Methods:
 parseInt(s) : returns a signed decimal integer value equivalent to
string s
 toString(i) : returns a new String object representing the integer i
parseInt(s) returns a signed decimal integer value equivalent to string s
toString(i) returns a new String object representing the integer i
byteValue() returns the value of this Integer as a byte
doubleValue() returns the value of this Integer as an double
floatValue() returns the value of this Integer as a float
intValue() returns the value of this Integer as an int
shortValue() returns the value of this Integer as a short
longValue() returns the value of this Integer as a long
int compareTo(int i) Compares the numerical value of the invoking object with that of i. Returns 0 if the
values are equal. Returns a negative value if the invoking object has a lower value.
Returns a positive value if the invoking object has a greater value.
static int compare(int
num1, int num2)
Compares the values of num1 and num2. Returns 0 if the values are equal. Returns
a negative value if num1 is less than num2. Returns a positive value if num1 is
greater than num2.
boolean equals(Object
intObj)
Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it
returns false
valueOf (), toHexString(), toOctalString() and
toBinaryString() Methods:
 This is another approach to create wrapper objects.
 We can convert from binary or octal or hexadecimal before
assigning value to wrapper object using two argument
constructor.
 Below program explains the method in details.
public class ValueOfDemo {
public static void main(String[] args) {
Integer intWrapper = Integer.valueOf("12345");
//Converting from binary to decimal.
Integer intWrapper2 = Integer.valueOf("11011", 2);
//Converting from hexadecimal to decimal.
Integer intWrapper3 = Integer.valueOf("D", 16);
System.out.println("Value of intWrapper Object: "+ intWrapper);
System.out.println("Value of intWrapper2 Object: "+ intWrapper2);
System.out.println("Value of intWrapper3 Object: "+ intWrapper3);
System.out.println("Hex value of intWrapper: " +
Integer.toHexString(intWrapper));
System.out.println("Binary Value of intWrapper2: "+
Integer.toBinaryString(intWrapper2));
}}
Character Class
 Character is a wrapper around a char.
 The constructor for Character is :
Character(char ch)
 Here, ch specifies the character that will be wrapped by the
Character object being created.
 To obtain the char value contained in a Character object,
callncharValue( ), shown here:
char charValue( );
 It returns the encapsulated character.
Converting primitive numbers to Object numbers
Constructor calling Conversion Action
Integer IntVal = new Integer(i); Primitive integer to Integer object
Float FloatVal = new Float(f); Primitive float to Float object
Double DoubleVal = new Double(d); Primitive double to Double object
Long LongVal = new Long(l); Primitive long to Long object
using constructor methods
Converting Object numbers to Primitive numbers
Method calling Conversion Action
int i = IntVal.intValue(); Object to primitive integer
float f = FloatVal.floatValue(); Object to primitive float
double d = DoubleVal.doubleValue(); Object to primitive double
long l = LongVal.longValue(); Object to primitive long
using typeValue() method
Converting Numbers to Strings
Method calling Conversion Action
str = Integer.toString(i); Primitive integer i to String str
str = Float.toString(f); Primitive float f to String str
str = Double.toString(d); Primitive double d to String str
str = Long.toString(l); Primitive long l to String str
using toString() method
Converting String Object in to Numeric Object
Method calling Conversion Action
IntVal = Integer.ValueOf(str); Convert String into Integer object
FloatVal = Float.ValueOf(str); Convert String into Float object
DoubleVal = Double.ValueOf(str); Convert String into Double object
LongVal = Long.ValueOf(str); Convert String into Long object
using static method ValueOf()
Converting Numeric Strings to Primitive numbers
Method calling Conversion Action
int i = Integer.parseInt(str); Converts String str into primitive integer i
long l = Long.parseLong(str); Converts String str into primitive long l
using Parsing method
public class WrapperDemo {
public static void main (String args[]){
Integer intObj1 = new Integer (25);
Integer intObj2 = new Integer ("25");
Integer intObj3= new Integer (35);
//compareTo demo
System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2));
System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3));
//Equals demo
System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2));
System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3));
Float f1 = new Float("2.25f");
Float f2 = new Float("20.43f");
Float f3 = new Float(2.25f);
System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2));
System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3));
//Addition of Integer with Float
Float f = intObj1.floatValue() + f1;
System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );
} }

More Related Content

Similar to vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx

Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
MLG College of Learning, Inc
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
Tanzeel Ahmad
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
adinathassociates
 
Javascript objects, properties and methods .pdf
Javascript objects, properties and methods .pdfJavascript objects, properties and methods .pdf
Javascript objects, properties and methods .pdf
daniljacobthomas
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
MiltonMolla1
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
stopgolook
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
sktambifortune
 
STL in C++
STL in C++STL in C++
STL in C++
Surya Prakash Sahu
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
shafat6712
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Array
ArrayArray
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat Sheet
Hortonworks
 

Similar to vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx (20)

Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
Built-in Classes in JAVA
Built-in Classes in JAVABuilt-in Classes in JAVA
Built-in Classes in JAVA
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
Javascript objects, properties and methods .pdf
Javascript objects, properties and methods .pdfJavascript objects, properties and methods .pdf
Javascript objects, properties and methods .pdf
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Array properties
Array propertiesArray properties
Array properties
 
Struktur data 1
Struktur data 1Struktur data 1
Struktur data 1
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
 
STL in C++
STL in C++STL in C++
STL in C++
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Array
ArrayArray
Array
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat Sheet
 
Arrays
ArraysArrays
Arrays
 

Recently uploaded

Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 

Recently uploaded (20)

Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 

vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx

  • 1. Vectors  Vector implements a DYNAMIC ARRAY.  Vectors can hold objects of any type and any number.  Vector class is contained in java.util package  Vector is different from ARRAY in two ways:- 1. Vector is synchronized. 2. It contains many legacy methods that are not part of the collection framework. 1. Enumeration. 2. Iterator
  • 2. Declaring VECTORS Vector list = new Vector(); Vector list = new Vector(int size); Vector list = new Vector(int size, int incr); Creates a default vector, which has an initial size 10. Creates a vector, whose initial capacity is specified by size. Creates a vector, whose initial capacity is specified by size and whose increment is specified by incr.
  • 3. Vectors (Contd….)  A vector can be declared without specifying any size explicitly.  A vector without size can accommodate an unknown number of items.  Even when size is specified, this can be overlooked and a different number of items may be put into the vector In contrast, An ARRAY must have its size specified.
  • 4. Sr.no Method Discription 1 void add(int index, Object element) Inserts the specified element at the specified position in this Vector. 2 boolean add(Object o) Appends the specified element to the end of this Vector. 3 boolean addAll(Collection c) Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator. 4 void addElement(Object obj) Adds the specified component to the end of this vector, increasing its size by one. 5 int capacity() Returns the current capacity of this vector. 6 void clear() Removes all of the elements from this Vector. 7 void copyInto(Object[] anArray) Copies the components of this vector into the specified array. 8 Object elementAt(int index) Returns the component at the specified index. 9 boolean equals(Object o) Compares the specified Object with this Vector for equality. 10 Object firstElement() Returns the first component (the item at index 0) of this vector.
  • 5. import java.util.*; public class VectorDemo { public static void main(String args[]) { Vector v = new Vector(3, 2); // initial size is 3, increment is 2 System.out.println("Initial size: " + v.size()); System.out.println("Initial capacity: " +v.capacity()); v.addElement(new Integer(2)); System.out.println("Capacity after four additions: " + v.capacity()); v.addElement(new Double(5.45)); System.out.println("Current capacity: " + v.capacity()); System.out.println("First element: " + v.firstElement()); System.out.println("Last element: " +v.lastElement()); } } Example
  • 6. Wrapper Classes  Most of the objects collection store objects and not primitive types.  Primitive types can be used as object when required.  As they are objects, they can be stored in any of the collection and pass this collection as parameters to the methods.
  • 7. Wrapper Class  Wrapper classes are classes that allow primitive types to be accessed as objects.  Wrapper class is wrapper around a primitive data type because they "wrap" the primitive data type into an object of that class.
  • 8. What is Wrapper Class?  Each of Java's eight primitive data types has a class dedicated to it.  They are one per primitive type.  Wrapper classes make the primitive type data to act as objects. Simple Type Wrapper class boolean Boolean char Character double Double float Float int Integer long Long short Short byte Byte
  • 9. Difference b/w Primitive Data Type and Object of a Wrapper Class  The following two statements illustrate the difference between a primitive data type and an object of a wrapper class: int x = 25; Integer y = new Integer(33); Clearly x and y differ by more than their values: • x is a variable that holds a value; • y is an object variable that holds a reference to an object. So, the following statement using x and y as declared above is not allowed: int z = x + y; // wrong!
  • 10.  The data field in an Integer object is only accessible using the methods of the Integer class.  One such method is intValue() method which returns an int equal to the value of the object, effectively "unwrapping" the  Integer object: int z = x + y.intValue(); // OK!
  • 11. Boxing and Unboxing  The wrapping is done by the compiler.  if we use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class.  Similarly, if we use a number object when a primitive is expected, the compiler un- boxes the object.  Example of boxing and unboxing: Integer x, y; x = 12; y = 15; System.out.println(x+y);  When x and y are assigned integer values, the compiler boxes the integers because x and y are integer objects.  In the println() statement, x and y are unboxed so that they can be added as integers.
  • 12. Integer Class  Constructors:  Integer(i) : constructs an Integer object equivalent to the integer i  Integer(s) : constructs an Integer object equivalent to the string s  Integer Class Methods:  parseInt(s) : returns a signed decimal integer value equivalent to string s  toString(i) : returns a new String object representing the integer i
  • 13. parseInt(s) returns a signed decimal integer value equivalent to string s toString(i) returns a new String object representing the integer i byteValue() returns the value of this Integer as a byte doubleValue() returns the value of this Integer as an double floatValue() returns the value of this Integer as a float intValue() returns the value of this Integer as an int shortValue() returns the value of this Integer as a short longValue() returns the value of this Integer as a long int compareTo(int i) Compares the numerical value of the invoking object with that of i. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value. static int compare(int num1, int num2) Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2. boolean equals(Object intObj) Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it returns false
  • 14. valueOf (), toHexString(), toOctalString() and toBinaryString() Methods:  This is another approach to create wrapper objects.  We can convert from binary or octal or hexadecimal before assigning value to wrapper object using two argument constructor.  Below program explains the method in details.
  • 15. public class ValueOfDemo { public static void main(String[] args) { Integer intWrapper = Integer.valueOf("12345"); //Converting from binary to decimal. Integer intWrapper2 = Integer.valueOf("11011", 2); //Converting from hexadecimal to decimal. Integer intWrapper3 = Integer.valueOf("D", 16); System.out.println("Value of intWrapper Object: "+ intWrapper); System.out.println("Value of intWrapper2 Object: "+ intWrapper2); System.out.println("Value of intWrapper3 Object: "+ intWrapper3); System.out.println("Hex value of intWrapper: " + Integer.toHexString(intWrapper)); System.out.println("Binary Value of intWrapper2: "+ Integer.toBinaryString(intWrapper2)); }}
  • 16. Character Class  Character is a wrapper around a char.  The constructor for Character is : Character(char ch)  Here, ch specifies the character that will be wrapped by the Character object being created.  To obtain the char value contained in a Character object, callncharValue( ), shown here: char charValue( );  It returns the encapsulated character.
  • 17. Converting primitive numbers to Object numbers Constructor calling Conversion Action Integer IntVal = new Integer(i); Primitive integer to Integer object Float FloatVal = new Float(f); Primitive float to Float object Double DoubleVal = new Double(d); Primitive double to Double object Long LongVal = new Long(l); Primitive long to Long object using constructor methods
  • 18. Converting Object numbers to Primitive numbers Method calling Conversion Action int i = IntVal.intValue(); Object to primitive integer float f = FloatVal.floatValue(); Object to primitive float double d = DoubleVal.doubleValue(); Object to primitive double long l = LongVal.longValue(); Object to primitive long using typeValue() method
  • 19. Converting Numbers to Strings Method calling Conversion Action str = Integer.toString(i); Primitive integer i to String str str = Float.toString(f); Primitive float f to String str str = Double.toString(d); Primitive double d to String str str = Long.toString(l); Primitive long l to String str using toString() method
  • 20. Converting String Object in to Numeric Object Method calling Conversion Action IntVal = Integer.ValueOf(str); Convert String into Integer object FloatVal = Float.ValueOf(str); Convert String into Float object DoubleVal = Double.ValueOf(str); Convert String into Double object LongVal = Long.ValueOf(str); Convert String into Long object using static method ValueOf()
  • 21. Converting Numeric Strings to Primitive numbers Method calling Conversion Action int i = Integer.parseInt(str); Converts String str into primitive integer i long l = Long.parseLong(str); Converts String str into primitive long l using Parsing method
  • 22. public class WrapperDemo { public static void main (String args[]){ Integer intObj1 = new Integer (25); Integer intObj2 = new Integer ("25"); Integer intObj3= new Integer (35); //compareTo demo System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2)); System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3)); //Equals demo System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2)); System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3)); Float f1 = new Float("2.25f"); Float f2 = new Float("20.43f"); Float f3 = new Float(2.25f); System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2)); System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3)); //Addition of Integer with Float Float f = intObj1.floatValue() + f1; System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f ); } }