0% found this document useful (0 votes)
7 views

05 VectorAndWrapper

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

05 VectorAndWrapper

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

JAVA PROGRAMMING

VECTOR CLASSES AND WRAPPER CLASSES.

 The package java.util contains a library of Java’s utility classes. One of them is Vector class.
 It implements a dynamic array which can hold the array of any type and any number.
 These objects do not have to be homogenous.
 Vector size can be grows autometically when we add the new element and shrink when we remove an element
from it.
 After this initial capacity is reached, and when we attempt to store an object in the vector, the vector automatically
allocates space for that object (increases capacity) plus extra room for additional objects.
 The amount of extra space allocated during each reallocation is determined by the increment that we specify
when we create the vector. If we don’t specify an increment, the vector’s size is doubled by each allocation cycle.
 The Vector class constructors.
o Vector() //Create Vector with initial capacity 10
o Vector( int size ) // Create Vector with initial capacity specified by given size
o Vector ( int size , int incr ) // Create Vector with initial capacity specified by given size and The increment
specifies the number of elements to allocate each time when new elements are added in the vector.
 Methods Of Vector Class (Consider v is a object of Vector Class ):
Method Prototype Description
void addElement(Object element) The object specified by element is added to the vector.
boolean removeElement(Object element) Removes element from the vector. If more than one
instance of the specifies object exists in the vector, then
it is the first one that is removed. It returns true if
successful and false if the object is not found
Object elementAt(int index) Returns the element at the location specified by index.
void insertElementAt(Object element, int Adds element to the vector at the location specified by
the index.
index)
int capacity() It returns the capacity of the vector
boolean contains(Object ele) It returns true if ‘element’ is contained by the vector, and
returns false if it is not.
void copyInto(Object array[]) The elements contained in the invoking vector are
copied into the array specified by ‘array’.
void ensureCapacity(int size) This method sets the minimum capacity of the vector to
‘size’.
Object firstElement( ) It returns the first element in the vector.
It returns the last element in the vector
Object lastElement()
int indexOf(Object element) It returns the index of the first occurrence of ‘element’. If
int indexOf(Object element, int start) the object is not found in the vector, –1 is returned.
void insertElementAt(Object element, int It adds ‘element’ to the vector at the location specified by
index) ‘index’.

Subject: Java Programming (Vector & Wrapper) Page 1 of 7


boolean isEmpty() This method returns true if the vector is empty and returns
false if it contains one or more elements.
int lastIndexOf(Object element) It returns the index of the last occurrence of ‘element’. If
int lastIndexOf(Object element, int start) the object is not in the vector, –1 is returned.
void removeAllElements() This method empties the vector. After is execution, the
size of the vector is zero.
boolean removeElement(Object element) It removes ‘element’ from the vector. If more than one
instance of the specified object exists in the vector, then
it is the first one that is removed. This method returns true
if successful and false if the object is not found.
void removeElementAt(int index) It removes the element at the location specified by ‘index’.
void setElementAt(Object element, int The location specified by ‘index’ is assigned ‘element’.
index)
void setSize(int size) It sets the number of elements in the vector to ‘size’. If the
new size is less than the old size, elements are lost. If the
new size is larger than the old size, ‘null’ elements are
added
int size() It returns the number of elements currently in the vector.
String toString() It returns the string equivalent of the vector.
void trimToSize() It sets the vector’s capacity equal to the number of
elements that it currently holds. That is it makes capacity
equal to size

 Explaination of addElement() method


o It is a method from Vector Class.
o It is used to add an object at the end of the Vector.
o Syntax: void addElement(Object);
o Example: v.addElement(new Integer(10)); // Here v is the Vector object,
o It will add Integer object with value 10 at the end of the Vector object ‘v’.

 Example Of Vector Class :


import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.addElement(new Integer(1));
v.addElement(new Double(2523));
v.addElement(new Float(3.55f));
v.addElement(“java”);
System.out.println("Size of vactor after four additions: " + v.size());
Subject: Java Programming (Vector & Wrapper) Page 2 of 7
v.removeElementAt(2);
v.removeElementAt(1);
System.out.println("Size of vactor after removed : " + v.size());
System.out.println("\nElements in vector:");
System.out.println(v);
}
}

Difference between Array and Vector

WRAPPER CLASSES
The primitive data types of Java such as int, char, float are not the part of any object hierarchy. They are always passed
by value to the method not by reference. Also, there is no way for two different methods to refer same instance of a data
type.
 For such purpose, it is necessary to create object representation of primitive data types. These object
representations of primitive data types are called as wrapper classes.
 In essence, these classes encapsulate or wrap the primitive data types within the class.
 All the wrapper classes are defined in package java.lang.
 Table shows the wrapper classes of respective data types.
Data Type Boolean char Double float int long short byte
Wrapper Class Boolean Character Double Float Integer Long Short Byte

The abstract class ‘Number’

Subject: Java Programming (Vector & Wrapper) Page 3 of 7


 It is a super class that is implemented by the classes that wrap the numeric types: byte, short, int, long, float, and
double.
 ‘Number’ has abstract methods that return the value of the object in each of the different number formats.
 These methods are shown here:
o byte byteValue( ) , double doubleValue( ) , float floatValue( ) ,
o int intValue( ) , long longValue( ) , short shortValue( )
 The values returned by all these methods can be rounded.
 Number has six concrete subclasses that hold explicit values of each numeric type: Double, Float, Byte, Short,
Integer, and Long.
 All these subclasses use the methods mentioned above.
All Wrapper Classes Constructor is as Follow
Float(double num) Double(double num) Byte(byte num)
Float(float num) Double(String str) throws NFE Byte(String str) throws NFE
Float(String str) throws NFE
Short(short num) Integer(int num) Long(long num)
Short(String str) throws NFE Integer(String str) throws NFE Long(String str) throws NFE
Character(char ch) Boolean(boolean boolValue)
Boolean(String boolString)

Note : In the above table, throws NFE means thorws NumberFormatException


Common Methods of Wrapper Class for Float, Double, Byte, Integer, Short, Long
 Float and Double are wrapper classes for floating-point values of type float and double, respectively.
 The Byte, Short, Integer, and Long are wrapper classes for byte, short, int, and long integer types.

Method Description
int compareTo(Byte obj) It compares the numerical value of the invoking object with that of ‘obj’. It
Returns 0 if the values are equal. -ve value if the invoking object has a
lower value. +ve value if the invoking object has a greater value.
int compareTo(Object Byteobj) Operates identically to compareTo(Byte) if ‘obj’ is of class Byte.
throws ClassCastException Otherwise, throws a ClassCastException.
boolean equals(Object ByteObj) It returns true if the invoking Byte object is equivalent to ‘ByteObj’.
Otherwise, it returns false.
int hashCode() This method returns the hash code for the invoking object.
static byte parseByte(String str) It returns the byte equivalent of the number contained in the string
throws NumberFormatException specified by ‘str’ using radix 10. It throws NumberFormatException if
number format of ‘str’ is not matched with byte constant.
static Byte valueOf(String str) It returns the Byte object that contains the value specified by the string
throws NumberFormatException in ‘str’. Otherwise throws NumberFormatException

Subject: Java Programming (Vector & Wrapper) Page 4 of 7


static String toString(byte num) It returns a string that contains the decimal equivalent of ‘num’.
String toString( ) It returns a string that contains the decimal equivalent of the invoking
object.
static Byte decode(String str) throws It returns a Byte object that contains the value specified by the string
NumberFormatEwxception in ‘str’
All the above methods are given in terms of Byte class. These can also be applied to other numeric classes.
Only we have to change Byte to Short or Integer or Long and byte to short or int or long.

Integer and Long class has added three useful methods:


Method Description
static String toBinaryString(int num) It returns a string that contains the binary equivalent of ‘num’.
static String toHexString(int num) It returns a string that contains the hexadecimal equivalent of ‘num’.

static String toOctalString(int num) It returns a string that contains the octal equivalent of ‘num’.

Methods of Character Wrapper Class


Method Description
char charValue() It returns the character which is stored in the Character class.
static boolean isDigit(char ch) It returns true if ‘ch’ is a digit. Otherwise, it returns false.
static boolean isLetter(char ch) It returns true if ‘ch’ is a letter. Otherwise, it returns false.
static boolean isLetterOrDigit(char ch) It returns true if ‘ch’ is a letter or a digit. Otherwise, it returns false.

static boolean isLowerCase(char ch) It returns true if ‘ch’ is a lowercase letter. Otherwise, it returns false.

static boolean isSpaceChar(char ch) It returns true if ‘ch’ is a Unicode space character. Otherwise, it returns false.

static boolean isTitleCase(char ch) It returns true if ‘ch’ is a Unicode title-case character. Otherwise, it returns false.

static boolean isUpperCase(char ch) It returns true if ‘ch’ is an uppercase letter. Otherwise, it returns false.

static boolean isWhitespace(char ch) It returns true if ‘ch’ is whitespace. Otherwise, it returns false.
static char toLowerCase(char ch) It returns lowercase equivalent of ‘ch’.
static char toTitleCase(char ch) It returns titlecase equivalent of ‘ch’.
static char toUpperCase(char ch) It returns uppercase equivalent of ‘ch’.

Boolean
This wrapper class contains the constants TRUE & FALSE, which define true and false Boolean objects.
Methods of Boolean Wrapper Class
Method Description
boolean booleanValue( ) It returns boolean equivalent value of the invoking object.
boolean equals(Object boolObj) It returns true if the invoking object is equivalent to ‘boolObj’.
Otherwise, it returns false.
`int hashCode( ) It returns the hash code for the invoking object.
Subject: Java Programming (Vector & Wrapper) Page 5 of 7
String toString( ) This method returns the string equivalent of the invoking object.
static String toString(boolean boolVal) It returns the string equivalent of ‘boolVal’.
static Boolean valueOf(boolean It returns the Boolean equivalent of ‘boolVal’.
boolVal)
static Boolean valueOf(String It returns true if ‘boolString’ contains the string “true” (in
boolString) uppercase or lowercase). Otherwise, it returns false

Example : demonstrates the use of Wrapper Class.


class WrapperFloat
{
public static void main(String args[])
{
Float f1 = new Float(5.6f);
float f = Float.parseFloat("6.3");
System.out.println("Float Value Is : "+f);
Integer x = new Integer(141);
byte b = x.byteValue();
System.out.println("Byte value: "+b);
int hash = x.hashCode();
System.out.println("Hash code: "+hash);
String bin = Integer.toBinaryString(59);
String oct = Integer.toOctalString(59);
String hex = Integer.toHexString(59);
System.out.println("Binary of 59: "+bin);
System.out.println("Octal of 59: "+oct);
System.out.println("Hex of 59: "+hex);
Character ch = new Character('X');
System.out.println(ch.charValue());
if(Character.isLowerCase('R'))
System.out.println("R is lower case");
else
System.out.println("R is upper case");
Boolean a = new Boolean("TRUE");
Boolean b = new Boolean(false);
System.out.println("First : "+a.booleanValue());
System.out.println("Second : "+b.booleanValue());
}
}

Wrapper Class:
 Objects like vector cannot handle primitive data types like int, float, long char and double.
 Wrapper classes are used to convert primitive data types into object types.
 Wrapper classes are contained in the java.lang package.
 The some of the wrapper classes are: Boolean, Integer, Character, Float etc.
 To convert integer number to string. Method is toString()
o String str = Integer.toString(i) –converts the integer i to string value.
 To convert numeric string to integer number: Method is parseInt()
o int i = Integer.parseInt(str) – converts the string value of numeric string str to int i.

Subject: Java Programming (Vector & Wrapper) Page 6 of 7


 To convert object number to primitive number using typevalue() method
o The method here is typeValue(), meaning that type can be the data type of the number.
o For example : if x is an Integer object with value 10, then it can be stored as primitive int y with the
method intValue() as
 Integer x = new Integer(10);
 int y = x.intValue();
o Similarly, it can be done with other numeric types as floatValue(), doubleValue() etc.

ENUMERATED TYPES: “What is Enum in java”


 Java Enum is type like class and interface and can be used to define a set of Enum constants.
 Enum constants are implicitly static and final and you can not change there value once created.
 Enum is a keyword you can not use as variable name.
 Benefits Of Enumarable Types.
 Enum in Java provides type-safety because you can not assign anything else other than predefined Enum
constants to an Enum variable.
 Enum has its own namespace: it must be stored in separate file with name of Enum.
 Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.
 Example :
FileName : Day.java
public enum Day
{
SUNDAY(1),MONDAY(2),TUESDAY(3),WEDNESDAY(4),THURSDAY(5),FRIDAY(6),SATURDAY(7);
private int dayno;
private Day(int dn)
{  Note that, Constructor in Enum must be declare as
dayno=dn; private.
}  You can add/remove constants easily.
public int getDayNo()
{  SUNDAY(1) : Parameter passing to Constructor
return(dayno);
}
};

FileName : TestDay.java
class TestDay {
public static void main(String args[]) {
Day day = Day.MONDAY; //Day Refance created and assign a constant value.
System.out.println(day.getDayNo());
}
}
Here, day is referance variable of Enum Day and it contains constant value of Day.MONDAY

Subject: Java Programming (Vector & Wrapper) Page 7 of 7

You might also like