0% found this document useful (0 votes)
24 views69 pages

Chapter 2.3

The document provides an overview of arrays in Java, detailing their structure, advantages, and disadvantages, as well as the syntax for declaring and initializing both single-dimensional and multidimensional arrays. It also covers Java's String and StringBuffer classes, highlighting their methods and functionalities for string manipulation. Additionally, it introduces jagged arrays and includes examples and homework assignments related to these topics.

Uploaded by

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

Chapter 2.3

The document provides an overview of arrays in Java, detailing their structure, advantages, and disadvantages, as well as the syntax for declaring and initializing both single-dimensional and multidimensional arrays. It also covers Java's String and StringBuffer classes, highlighting their methods and functionalities for string manipulation. Additionally, it introduces jagged arrays and includes examples and homework assignments related to these topics.

Uploaded by

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

Unit II

Derived Syntactical
Constructs in Java

Mr. R. M. Patil
SY CO, JPR
2023-2024
2.3. Array in Java
 Normally, an array is a collection of similar type of
elements which has contiguous memory location.

 Java array is an object which contains elements of a


similar data type. Additionally, The elements of an array
are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store
only a fixed set of elements in a Java array.

 Array in Java is index-based, the first element of the


array is stored at the 0th index, 2nd element is stored on
1st index and so on.
2.3. Array in Java
 Unlike C/C++, we can get the length of the array using
the length member.
 In Java, array is an object of a dynamically generated
class. Java array inherits the Object class, and implements
the Serializable as well as Cloneable interfaces. We can
store primitive values or objects in an array in Java. Like
C/C++, we can also create single dimensional or
multidimensional arrays in Java.
2.3. Array in Java
Advantages:

• Code Optimization: It makes the code optimized, we


can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index
position.

Disadvantages:

•Size Limit: We can store only the fixed size of elements in


the array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in Java which
grows automatically.
2.3. Array in Java

Types of Array
Single (One) Multidimensional
Dimensional Array Array
2.3. Array in Java – 1. Single Dimensional Array

Syntax to Declare an
Array in Java: Instantiation of an Array in Java:
dataType[] arr; (or) arrayRefVar=new datatype[size];
dataType []arr; (or)
dataType arr[];
2.3. Array in Java – 1. Single Dimensional Array
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation Output:

a[0]=10; //initialization 10
a[1]=20; 20
a[2]=70;
a[3]=40;
70
a[4]=50; 40
50
for(int i=0;i<a.length;i++) //length is the property of array
{
System.out.println(a[i]);
}
}
}
2.3. Array in Java – 1. Single Dimensional Array

We can declare, instantiate and initialize the java array


together by:

int a[]={33,3,4,5};

//declaration, instantiation and initialization


2.3. Array in Java – 1. Single Dimensional Array

class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5}; //declaration, instantiation and initialization

//printing array Output:

for(int i=0;i<a.length;i++) //length is the property of array 33


{ 3
System.out.println(a[i]); 4
} 5
}
}
2.3. Array in Java – 1. Single Dimensional Array

For-each Loop for Java Array:

class Testarray1
{
public static void main(String args[]) Output:
{
33
int arr[]={33,3,4,5};
3
4
for(int i : arr)
5
{
System.out.println(i);
}
}
}
2.3. Array in Java – 2. Multidimensional Array

Syntax to Declare an
Array in Java:

dataType[][] arrayRefVar; (or) Instantiation of an Array in Java:

dataType [][]arrayRefVar; (or) int[][] arr=new int[3][3];

dataType arrayRefVar[][]; (or) //3 row and 3 column

dataType []arrayRefVar[];
2.3. Array in Java – 2. Multidimensional Array

Instantiation of an Array in Java:

int[][] arr=new int[3][3];

Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
2.3. Array in Java – 2. Multidimensional Array
class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; Output:
for(int i=0;i<3;i++)
{ 123
for(int j=0;j<3;j++) 245
{
System.out.print(arr[i][j]+" "); 445
}
System.out.println();
}
}
}
2.3. Array in Java - Cloning an Array in Java
Since, Java array implements the Cloneable interface,
we can create the clone of the Java array.

 If we create the clone of a single-dimensional array, it


creates the deep copy of the Java array. It means, it will
copy the actual value.

int a []={33,3,4,5};

int b[]=a.clone();
2.3. Array in Java - Cloning an Array in Java
class test
{
public static void main(String args[]) Output:
{ a[0]=10
int []a = {10,20,30,40,50}; a[1]=20
int []b = a.clone(); a[2]=30
a[3]=40
for(int i=0; i<a.length;i++) a[4]=50
System.out.println("a["+i+"]="+a[i]); b[0]=10
b[1]=20
for(int i=0; i<b.length;i++) b[2]=30
System.out.println("b["+i+"]="+b[i]);
b[3]=40
}
}
b[4]=50
2.3. Array in Java - Jagged Array in Java

 A jagged array is an array of arrays such that member arrays can


be of different sizes, i.e., we can create a 2-D array but with a
variable number of columns in each row.

 These types of arrays are also known as Jagged arrays.

Consider the below example in


which each row consists of
different number of elements.

First row contains 4 elements,


second row contains 2 elements
and third row contains 3 elements.
2.3. Array in Java - Jagged Array in Java
Declaration and Initialization of Jagged array

datatype[][] arrayName = new datatype[numRows][];


arrayName[0] = new datatype[numColumns1];
arrayName[1] = new datatype[numColumns2];
...
arrayName[numRows-1] = new datatype[numColumnsN];

int[][] a = new int[4][];


// Set the number of columns for each row
a[0] = new int[1];
a[1] = new int[2];
Example
a[2] = new int[2];
a[3] = new int[3];
2.3. Array in Java - Jagged Array in Java
class test for(int i=0;i<a.length;i++)
{ {
public static void main(String args[]) for(int j=0;j<a[i].length;j++)
{ {
int [][]a = new int [3][]; System.out.print(a[i][j]+" ");
a[0] = new int [1]; }
a[1] = new int [2]; System.out.println();
a[2] = new int [3]; }
}
int b = 1; }

for(int i=0; i<a.length; i++)


{
for(int j=0; j<a[i].length; j++) OUTPUT
{
a[i][j] = b; 1
23
b++;
456
}
}
HOMEWORK

1. Explain 2-D array with an example.


4M

2. Program to illustrate Jagged array.


4M
2.3. Java String
 In Java, string is basically an object that represents
sequence of char values.

 An array of characters works same as Java string. For


example:
char[] ch={‘s',‘i',‘t',‘p',‘o',‘l',‘y’};
String s=new String(ch);

is same as:

String s=“sitpoly";
2.3. Java String Class
 The java.lang.String class provides a lot of methods to
work on string.

 By the help of these methods, we can perform


operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.

 Java String is a powerful concept because everything is


treated as a string if you submit any form in window
based, web based or mobile application.
2.3. Java String Class Methods
Sr
No Method Call Task Performed

1 s2 = s1.toLowerCase(); Converts the string s1 to all lowercase

2 s2 = s1.toUpperCase(); Converts the string s1 to all uppercase

3 s2 = s1.replace(‘x’, ‘y’); Replace all appearances of x with y


Remove whitespaces at the beginning and end
4 s2 = s1.trim(); of the string s1

5 s1.equals(s2) Returns ‘true’ if s1 is equal to s2


Returns ‘true’ if s1=s2, ignoring the case of
6 s1.equalsIgnoreCase(s2) characters

7 s1.length() Gives the length of s1

8 s1.charAt(n) Gives nth character of s1


2.3. Java String Class Methods
Sr
No Method Call Task Performed
Returns negative if s1<s2, positive if s1>s2 and
9 s1.compareTo(s2) zero if s1 is equal s2
10 s1.concat(s2) Concatenates s1 and s2
11 s1.substring(n) Gives substring starting from nth character
Gives substring starting from nth character to
12 s1.substring(n, m) mth character (Not including mth)
Creates the string object of the parameter p
13 String.Valueof(p) (Simple type or object)
14 p.toString() Creates the string representation of the object p
Gives the position of the first occurrence of ‘x’ in
15 s1.indexof(‘x’) the string s1
Gives the position of ‘x’ that occurs after nth
16 s1.indexof(‘x’, n)
position in the string s1
2.3. Java String Class Methods - Example
String s="Sachin";

System.out.println(s.toUpperCase()); //SACHIN

System.out.println(s.toLowerCase()); //sachin

System.out.println(s); //Sachin(no change in original)

String s=" Sachin ";

System.out.println(s); // Sachin

System.out.println(s.trim()); //Sachin
2.3. Java String Class Methods - Example
String s="Sachin";

System.out.println(s.startsWith("Sa")); //true

System.out.println(s.endsWith("n")); //true

String s="Sachin";

System.out.println(s.charAt(0)); //S

System.out.println(s.charAt(3)); //h

String s="Sachin";

System.out.println(s.length()); //6
2.3. Java String Class Methods - Example

String s1="Java is a programming language. Java is a platform. Java is an Island.";

String replaceString=s1.replace("Java","Kava");

//replaces all occurrences of "Java" to "Kava"

System.out.println(replaceString);
2.3. Java String Class Methods - Example
import java.io.*;
import java.util.*;

class test
{
public static void main (String[] args)
{
String s= "sitpolytechnic";

System.out.println("String length = " + s.length());


System.out.println("Character at 3rd position = "+ s.charAt(3));
System.out.println("Substring " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));

String s1 = "sit";
String s2 = "yadrav";
System.out.println("Concatenated string = " +s1.concat(s2));
2.3. Java String Class Methods - Example
String s4 = "Learn Share Learn";

System.out.println("Index of Share " +s4.indexOf("Share"));


System.out.println("Index of a = " + s4.indexOf('a',3));

Boolean out = s1.equals(s2);


System.out.println("Checking Equality " + out);

out = "SiT".equalsIgnoreCase("sit");
System.out.println("Checking Equality(IgnoreCase) " + out);

int out1 = s1.compareTo(s2);


System.out.println("the difference between ASCII value is="+out1);
}
}
HOMEWORK

1. Explain use of following methods- a.indexOf()


b.charAt() c. subString() d. replace() e. compareTo()
f. equalsIgnoreCase() g. length()
W14, W15, S16, S17, W17 - 4M

2. Write a java program to implement functions of string


a. Calculate length of string
b. Compare between strings.

Or Program to String class methods


S18 - 4M
2.3. Java StringBuffer Class
 StringBuffer is a peer class of String that provides
much of the functionality of strings.
 String represents fixed-length, immutable character
sequences while StringBuffer represents growable and
writable character sequences.
 StringBuffer may have characters and substrings
inserted in the middle or appended to the end.
 It will automatically grow to make room for such
additions and often has more characters pre-allocated
than are actually needed, to allow room for growth.
2.3. Java StringBuffer Class - Constructors
1. StringBuffer(): It reserves room for 16 characters without
reallocation.

StringBuffer s=new StringBuffer();

2. StringBuffer(int size): It accepts an integer argument that


explicitly sets the size of the buffer.

StringBuffer s=new StringBuffer(20);

3. StringBuffer(String str): It accepts a String argument that sets


the initial contents of the StringBuffer object and reserves room for
16 more characters without reallocation.

StringBuffer s=new StringBuffer(“sitpoly");


2.3. Java StringBuffer Class - Methods
1. length( ) and capacity( ): The length of a StringBuffer can be
found by the length( ) method, while the total allocated capacity
can be found by the capacity( ) method.
class stbuff
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("SitPoly");
int p = s.length();
int q = s.capacity();
System.out.println("Length of string SitPoly=" + p);
System.out.println("Capacity of string SitPoly=" + q);
}
} Output:
Length of string SitPoly=7
Capacity of string SitPoly=23
2.3. Java StringBuffer Class - Methods
2. append( ): It is used to add text at the end of the existence text.

import java.io.*;
class stbuff
{
public static void main(String[] args)
{ Output:
sitpoly
StringBuffer s = new StringBuffer("sit"); sitpoly1
s.append("poly");
System.out.println(s);
s.append(1);
System.out.println(s);
}
}
2.3. Java StringBuffer Class - Methods
3. insert( ): It is used to insert text at the specified index position.
import java.io.*;
class stbuff Output:
sitpoforlytechnic
{
11sitpoforlytechnic
public static void main(String[] args) 11rahulsitpoforlytechnic
{
StringBuffer s = new StringBuffer("sitpolytechnic");
s.insert(5, "for");
System.out.println(s);
s.insert(0, 11);
System.out.println(s);
char a_arr[] = { 'r', 'a', 'h', 'u', 'l' };
s.insert(2, a_arr); //insert character array at offset 9
System.out.println(s);
}
}
2.3. Java StringBuffer Class - Methods
4. reverse( ): It can reverse the characters within a StringBuffer
object using reverse( ).This method returns the reversed object on
which it was called. .

import java.io.*; Output:


class stbuff yloptis
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("sitpoly");
s.reverse();
System.out.println(s);
}
}
2.3. Java StringBuffer Class - Methods
5. delete( ) & deleteCharAt(): It can delete characters within a
StringBuffer by using the methods delete() and deleteCharAt().

The delete() method deletes a sequence of characters from the


invoking object.

Here, start Index specifies the index of the first character to remove,
and end Index specifies an index one past the last character to
remove. Thus, the substring deleted runs from start Index to
endIndex–1.

The resulting StringBuffer object is returned.

The deleteCharAt( ) method deletes the character at the index


specified by loc. It returns the resulting StringBuffer object.
2.3. Java StringBuffer Class - Methods

import java.io.*;
class stbuff
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("sitpolytechnic");
s.delete(0, 5);
System.out.println(s);
s.deleteCharAt(7); Output:
System.out.println(s);
lytechnic
} lytechnc
}
2.3. Java StringBuffer Class - Methods
6. replace() : It can replace one set of characters with another set
inside a StringBuffer object by calling replace( ). The substring being
replaced is specified by the indexes start Index and endIndex.

import java.io.*; Output:


class stbuff sitpoare
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("sitpoly");
s.replace(5, 8, "are");
System.out.println(s);
}
}
2.3. Java StringBuffer Class - Methods

7. charAt(int index): This method returns the char value in this


sequence at the specified index.

System.out.println(s.charAt(2));

8. void setLength(int len): Sets the length of the buffer within


StringBuffer object.

s.setLength(30);
2.3. String Vs. StringBuffer Class

Parameter String StringBuffer

The length of the The length of the


Basic string object is fixed. StringBuffer can be
increased.
String object is StringBuffer object is
Modification immutable. mutable.
It is slower in the It is faster in the
Performance process of process of
concatenation. concatenation.
Requires more
Memory memory. Requires less memory.
HOMEWORK

1. Perform following string / string buffer operations,


write java program.
i. Accept password from user.
ii. Check if password is correct then display “Good”,
else display “Wrong”
iii. Display the password in reverse order.
iv. Append password with ‘Welcome’
W16 - 4M

2. Compare String Class and StringBuffer class with any


four points.
S15 – 4M
2.3. Vector class in Java
 Vector is like the dynamic array which can grow or
shrink its size.

 Unlike array, we can store n-number of elements in it


as there is no size limit.

 It is found in the java.util package and implements


the List interface.

 Vector implements a dynamic array that means it can


grow or shrink as required. Like an array, it contains
components that can be accessed using an integer index.
2.3. Vector class in Java

Constructor Description

It constructs an empty vector with


vector()
the default size as 10.
It constructs an empty vector with
the specified initial size and with
vector(int size)
its capacity increment equal to
zero.
It constructs an empty vector with
vector(int size, int
the specified initial size and size
sizeIncrement)
increment.
It constructs a vector that contains
Vector( Collection c)
the elements of a collection c.
2.3. Vector class in Java- Methods
SN Method Description
It is used to append the specified element in the given
1) add()
vector.
It is used to append all of the elements in the specified
2) addAll()
collection to the end of this Vector.
It is used to append the specified component to the end of
3) addElement() this vector. It increases the vector size by one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

6) clone() It returns a clone of this vector.

7) contains() It returns true if the vector contains the specified element.


It returns true if the vector contains all of the elements in
8) containsAll()
the specified collection.
It is used to copy the components of the vector into the
9) copyInto()
specified array.
10) elementAt() It is used to get the component at the specified index.
2.3. Vector class in Java- Methods
It returns an enumeration of the components of a vector.
11) elements()
It is used to increase the capacity of the vector which is in
use, if necessary. It ensures that the vector can hold at least
12) ensureCapacity()
the number of components specified by the minimum
capacity argumen.
It is used to compare the specified object with the vector for
13) equals()
equality.
14) firstElement() It is used to get the first component of the vector.
It is used to perform the given action for each element of the
15) forEach() Iterable until all elements have been processed or the action
throws an exception.
It is used to get an element at the specified position in the
16) get()
vector.
17) hashCode() It is used to get the hash code value of a vector.
It is used to get the index of the first occurrence of the
18) indexOf() specified element in the vector. It returns -1 if the vector does
not contain the element.
It is used to insert the specified object as a component in the
19) insertElementAt()
given vector at the specified index.
20) isEmpty() It is used to check if this vector has no components.
2.3. Vector class in Java- Methods
It is used to get an iterator over the elements in the list in
21) iterator()
proper sequence.
22) lastElement() It is used to get the last component of the vector.
It is used to get the index of the last occurrence of the
23) lastIndexOf() specified element in the vector. It returns -1 if the vector
does not contain the element.
It is used to get a list iterator over the elements in the list
24) listIterator()
in proper sequence.
It is used to remove the specified element from the vector.
25) remove()
If the vector does not contain the element, it is unchanged.
It is used to delete all the elements from the vector that
26) removeAll()
are present in the specified collection.
It is used to remove all elements from the vector and set
27) removeAllElements()
the size of the vector to zero.
It is used to remove the first (lowest-indexed) occurrence of
28) removeElement()
the argument from the vector.
29) removeElementAt() It is used to delete the component at the specified index.
It is used to remove all of the elements of the collection
30) removeIf()
that satisfy the given predicate.
2.3. Vector class in Java- Methods
It is used to delete all of the elements from the vector whose index is between
31) removeRange() fromIndex, inclusive and toIndex, exclusive.

It is used to replace each element of the list with the result of applying the operator
32) replaceAll() to that element.

It is used to retain only that element in the vector which is contained in the specified
33) retainAll() collection.

It is used to replace the element at the specified position in the vector with the
34) set() specified element.

It is used to set the component at the specified index of the vector to the specified
35) setElementAt()
object.
36) setSize() It is used to set the size of the given vector.

37) size() It is used to get the number of components in the given vector.

38) sort() It is used to sort the list according to the order induced by the specified Comparator.
It is used to create a late-binding and fail-fast Spliterator over the elements in the
39) spliterator()
list.
It is used to get a view of the portion of the list between fromIndex, inclusive, and
40) subList() toIndex, exclusive.

41) toArray() It is used to get an array containing all of the elements in this vector in correct order.

42) toString() It is used to get a string representation of the vector.


43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.
2.3. Vector class in Java
import java.util.*;
public class stbuff
{
public static void main(String args[])
{
Vector v = new Vector();
v.add("Tiger");
v.add("Lion");
Output:
v.add("Dog");
v.add("Elephant"); Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

v.addElement("Rat");
v.addElement("Cat");
v.addElement("Deer");

System.out.println("Elements are: "+v);


}
}
2.3. Vector class in Java – Ex. 02
import java.util.*;
public class VectorExample1
{
public static void main(String args[])
{
Vector v= new Vector(4);

v.add("Tiger");
v.add("Lion");
v.add("Dog");
v.add("Elephant");

System.out.println("Size is: "+v.size());


System.out.println("Default capacity is: "+v.capacity());

System.out.println("Vector element is: "+v);


2.3. Vector class in Java – Ex. 02
v.addElement("Rat");
v.addElement("Cat");
v.addElement("Deer");

System.out.println("Size after addition: "+v.size());


System.out.println("Capacity after addition is: "+v.capacity());

System.out.println("Elements are: "+v);


2.3. Vector class in Java – Ex. 02
if(v.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +v.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}

System.out.println("The first animal of the vector is = "+v.firstElement());

System.out.println("The last animal of the vector is = "+v.lastElement());

}
}
2.3. Vector class in Java – Ex. 03
import java.util.*;
public class VectorExample2
{
public static void main(String args[])
{
Vector v = new Vector();
v.add(100);
v.add(200);
v.add(300);
v.add(200);
v.add(400);
v.add(500);
v.add(600);
v.add(700);
System.out.println("Values in vector: " +v);
2.3. Vector class in Java – Ex. 03

//use remove() method to delete the first occurrence of an element

System.out.println("Remove first occurrence of element 200: "+v.remove((Integer)200));

//Display the vector elements after remove() method

System.out.println("Values in vector: " +v);

//Remove the element at index 4

System.out.println("Remove element at index 4: " +v.remove(4));

System.out.println("New Value list in vector: " +v);


//Remove an element 2.3. Vector class in Java – Ex. 03

v.removeElementAt(5);

//Checking vector and displays the element

System.out.println("Vector element after removal: " +v);

//Get the hashcode for this vector

System.out.println("Hash code of this vector = "+v.hashCode());

//Get the element at specified index

System.out.println("Element at index 1 is = "+v.get(1));


}
}
Another way to create a vector

Vector<DataType> vector = new Vector<>();

Here, Type indicates the type of a linked list.

For example,

// create Integer type linked list

Vector<Integer> vector= new Vector<>();

// create String type linked list

Vector<String> vector= new Vector<>();


import java.util.Vector;
class demo 2.3. Vector class in Java – Ex. 04
{
public static void main(String[] args) {
Vector<String> v1= new Vector<>();

// Using the add() method


v1.add("Dog");
v1.add("Horse");

// Using index number


v1.add(1, "Cat");
System.out.println("Vector: " + v1);

// Using addAll()
Vector<String> v2 = new Vector<>();
v2.add("Crocodile");

v2.addAll(v1);
System.out.println("New Vector: " + v2);
}
}
HOMEWORK

1. Explain any four methods of vector with example.


W14 - 4M
2. Write a program to implement a vector class and its
method for adding and removing elements. After
remove display remaining list.
S16 – 4M
3. Write a program to add 2 integer, 2 string and 2 float
objects to a victor. Remove element specified by user
and display the list.
S17, W22 – 4M
4. Differentiate between array and vector.
W14, S15, W15, W16 – 4M
2.3. Wrapper class in Java
 The wrapper class in Java provides the mechanism to
convert primitive into object and object into primitive.

 Since J2SE 5.0, autoboxing and unboxing feature


convert primitives into objects and objects into primitives
automatically.

 The automatic conversion of primitive into an object is


known as autoboxing and vice-versa unboxing.
2.3. Wrapper class in Java
Use of Wrapper classes in Java:
Java is an object-oriented programming language, so we need to
deal with objects many times like in Collections, Serialization,
Synchronization, etc. Let us see the different scenarios, where we
need to use the wrapper classes.

o Change the value in Method: Java supports only call by value. So,
if we pass a primitive value, it will not change the original value.
But, if we convert the primitive value in an object, it will change the
original value.

o Serialization: We need to convert the objects into streams to


perform the serialization. If we have a primitive value, we can
convert it in objects through the wrapper classes.
2.3. Wrapper class in Java
o Synchronization: Java synchronization works with objects in
Multithreading.

o java.util package: The java.util package provides the utility


classes to deal with objects.

o Collection Framework: Java collection framework works with


objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue,
ArrayDeque, etc.) deal with objects only.
2.3. Wrapper class in Java
The eight classes of the java.lang package are known as wrapper classes in Java.
The list of eight wrapper classes are given below:

Primitive Data Type Wrapper Class


byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
2.3. Wrapper class in Java – 1. Autoboxing
 The automatic conversion of primitive data type into its
corresponding wrapper class is known as autoboxing.

 For example, byte to Byte, char to Character, int to Integer etc

Example:
int a=20;

Integer i = Integer.valueOf(a); //converting int into Integer explicitly

Integer j = a;

//autoboxing, now compiler will write Integer.valueOf(a) internally


2.3. Wrapper class in Java – 2. Unboxing

 The automatic conversion of wrapper type into its corresponding


primitive type is known as unboxing.

 It is the reverse process of autoboxing.

Example:
Integer a = 3;

int i = a.intValue(); //converting into Integer to int explicitly

int j = a;

//unboxing, now compiler will write a.intValue() internally


2.3. Wrapper class in Java – Example
//
Autoboxing: Converting pri //Unboxing: Converting
mitives into objects Objects to Primitives
byte b=10; Byte byteobj=b; byte bytevalue=byteobj;

short s=20; Short shortobj=s; short shortvalue=shortobj;

int i=30; Integer intobj=i; int intvalue=intobj;

long l=40; Long longobj=l; long longvalue=longobj;

float f=50.0F; Float floatobj=f; float floatvalue=floatobj;

double d=60.0D; Double doubleobj=d; double doublevalue=doubleobj;

char c='a'; Character charobj=c; char charvalue=charobj;

boolean b2=true; Boolean boolobj=b2; boolean boolvalue=boolobj;


2.3. Java Enum
 The Enum in Java is a data type which contains a fixed
set of constants.

 It can be used for days of the -


week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) ,
directions (NORTH, SOUTH, EAST, and WEST),
season (SPRING, SUMMER, WINTER, and AUTUMN or
FALL),
colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK)
etc.
2.3. Java Enum
 According to the Java naming conventions, we should
have all constants in capital letters.

 So, we have enum constants in capital letters.

 Java Enums can be thought of as classes which have a


fixed set of constants (a variable that does not change).

 The Java enum constants are static and final implicitly.


It is available since JDK 1.5.
2.3. Java Enum
public class stbuff
{
enum Level
{ Output:
LOW,
MEDIUM, MEDIUM
HIGH
}

public static void main(String[] args)


{
Level myVar = Level.MEDIUM;
System.out.println(myVar);
}
}
2.3. Java Enum
class stbuff
{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args)


{
Output:
for (Season s : Season.values())
{ WINTER
System.out.println(s); SPRING
} SUMMER
} FALL
}
HOMEWORK

1. Define Wrapper Class.


S15, W17 - 4M
2. Define Enumerated Types in Java
2M

You might also like