0% found this document useful (0 votes)
2 views38 pages

Oopjava Unit 2

The document provides a comprehensive overview of Object Oriented Programming in Java, focusing on arrays, collections, and string handling. It covers the declaration, initialization, and memory storage of single and multi-dimensional arrays, along with examples of accessing and modifying elements. Additionally, it introduces jagged arrays, explaining their structure and how to declare and initialize them.
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)
2 views38 pages

Oopjava Unit 2

The document provides a comprehensive overview of Object Oriented Programming in Java, focusing on arrays, collections, and string handling. It covers the declaration, initialization, and memory storage of single and multi-dimensional arrays, along with examples of accessing and modifying elements. Additionally, it introduces jagged arrays, explaining their structure and how to declare and initialize them.
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

Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&A.

Neelima

Object Oriented Programming Through JAVA


[B20CS2103]
Unit-II
_______________________________________________________________________________________________________
SYLLABUS:
Arrays: Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer
Memory, Accessing Elements of Arrays, Two-dimensional Arrays and Variable Size Arrays.
Collections: Array List, HashMap and HashSet.
String Handling in Java: Introduction, Methods in String class, String Constant Pool and
String Buffer class, Wrapper classes, Type Conversion.
_______________________________________________________________________________________________________

Arrays: Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

Declaration of Arrays

To declare an array, you need to specify the type of elements it will hold, followed by square
brackets []. There are two ways to declare an array in Java:

// Syntax 1: Declare an array of integers

int[] numbers;

// Syntax 2: Declare an array of integers (alternative syntax)

int numbers[];

Both syntaxes are valid, but the first one (int[] numbers;) is more commonly used.

Initialization of Arrays
Once an array is declared, it must be initialized before it can be used. Initialization can be
done in a few different ways.

Initialize with a specified size

This method allocates memory for a specific number of elements, but does not assign
values:

// Initialize an array of integers with size 5

int[] numbers = new int[5];

In this case, the array numbers has 5 elements, each initialized to the default value for the
data type (0 for integers).

Initialize with specific values

You can also initialize an array with a set of values at the time of declaration:

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 1


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

// Initialize an array of integers with specific values

int[] numbers = {1, 2, 3, 4, 5};

This creates an array with the specified elements, and the size of the array is automatically
determined by the number of elements provided.

Initialize using new keyword with specific values

Alternatively, you can initialize an array using the new keyword along with specific values:

// Initialize an array of integers using the 'new' keyword

int[] numbers = new int[]{1, 2, 3, 4, 5};

Let's see the simple example to print this array.

Example:1

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}
}

Output:
33
3
4
5

Example:2

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array at run time
import [Link].*;
class Testarray2
{
public static void main(String args[])
{
int a[]=new int[4];//declaration, instantiation
Scanner sc=new Scanner([Link]);
[Link]("Enter Array Elements:");

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 2


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

for(int i=0;i<[Link];i++)//length is the property of array


a[i]=[Link]();//initialization of array values from the console
//printing array
[Link]("Array Elements are:");
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}
}

Output:
Enter Array Elements:
33
3
4
5
Array Elements are:
33
3
4
5

Types of Array in java

There are two types of array.


o Single Dimensional Array
o Multidimensional Array

Single Dimensional Array

Syntax to Declare an Array in Java


dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Multidimensional Array

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 3


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

Storage of Array in Computer Memory

1D Array Memory Storage


For a one-dimensional (1D) array, the elements are stored sequentially in contiguous
memory locations. If you declare an array in Java like this:

int[] numbers = {10, 20, 30, 40, 50};

Here’s how it would be stored in memory:


• The memory addresses for the elements of the array are consecutive.
• If the base address of the array (the address of the first element, numbers[0]) is A, then
the address of the next element, numbers[1], will be A + sizeof(int), where sizeof(int) is
the size of an integer in bytes (usually 4 bytes in Java).

So, if the base address of numbers is 1000, the elements would be stored as follows:

Element Value Memory Address


numbers[0] 10 1000
numbers[1] 20 1004
numbers[2] 30 1008
numbers[3] 40 1012
numbers[4] 50 1016

Accessing Array Elements

Since array elements are stored contiguously, accessing an element is very efficient. If you
know the base address (starting address) of the array, you can compute the memory
address of any element using the formula:

Address of element=Base Address+(i×Size of element)

Where i is the index of the element.

For example, to access the third element (numbers[2]), the address would be:

Address of numbers[2]=1000+(2×4)=1008

2D Array Memory Storage

In a two-dimensional (2D) array, the elements are stored in a row-major or column-major


order. In Java, arrays are stored in row-major order by default, meaning that the elements
of the array are stored row by row.

For example, consider the following 2D array:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 4


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

{7, 8, 9}
};

In memory, this 2D array is stored in a flattened form, where elements of the first row are
stored first, followed by elements of the second row, and so on:

Row & Column Value Memory Address


matrix[0][0] 1 1000
matrix[0][1] 2 1004
matrix[0][2] 3 1008
matrix[1][0] 4 1012
matrix[1][1] 5 1016
matrix[1][2] 6 1020
matrix[2][0] 7 1024
matrix[2][1] 8 1028
matrix[2][2] 9 1032

Multi-Dimensional Arrays (General Case)

For higher-dimensional arrays (e.g., 3D arrays), the storage principle is the same. The
elements are laid out in memory in a row-major order (or column-major, depending on the
language), but the calculations for the memory address become more complex.

For a 3D array arr[x][y][z], the address of an element at position (i, j, k) can be computed
using:

Address=Base Address+[(i×(y×z))+(j×z)+k]×Size of element

Accessing Elements of Arrays

Accessing Elements in a 1D Array


To access an element in a one-dimensional (1D) array, use the array name followed by the
index of the element inside square brackets [].

Example:

public class Main


{
public static void main(String[] args)
{
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};

// Access the first element (index 0)


int firstElement = numbers[0];
[Link]("First element: " + firstElement); // Output: 10

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 5


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

// Access the third element (index 2)


int thirdElement = numbers[2];
[Link]("Third element: " + thirdElement); // Output: 30
}
}

Output:
First element: 10
Third element: 30

Modifying Elements in a 1D Array


You can also modify elements in an array by assigning a new value to a specific index.

Example:

public class Main


{
public static void main(String[] args)
{
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};

// Modify the second element (index 1)


numbers[1] = 25;
[Link]("Modified second element: " + numbers[1]); // Output: 25
}
}
Output:
Modified second element: 25

Accessing Elements in a 2D Array


In a two-dimensional (2D) array, elements are accessed using two indices: one for the row
and one for the column.

Example:
public class Main
{
public static void main(String[] args)
{
// Declare and initialize a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Access the element at the first row, second column (index 0, 1)


int element = matrix[0][1];
[Link]("Element at matrix[0][1]: " + element); // Output: 2

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 6


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

// Access the element at the third row, third column (index 2, 2)


int anotherElement = matrix[2][2];
[Link]("Element at matrix[2][2]: " + anotherElement); // Output: 9
}
}
Output:
Element at matrix[0][1]: 2
Element at matrix[2][2]: 9

Modifying Elements in a 2D Array


You can modify elements in a 2D array by specifying the row and column indices and
assigning a new value.

Example:

public class Main


{
public static void main(String[] args)
{
// Declare and initialize a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Modify the element at the second row, third column (index 1, 2)


matrix[1][2] = 10;
[Link]("Modified element at matrix[1][2]: " + matrix[1][2]);// Output: 10
}
}

Output:
Modified element at matrix[1][2]:10

Variable size Arrays


Jagged Arrays are special types of Multidimensional arrays which have variable number
of columns. It is an array of arrays where each element is an array and can be of a different
size.

What is a Jagged Array?


A jagged Array is an array of arrays where each element is an array. It is a special type of
Multidimensional array where there are a variable number of columns in each row.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 7


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

They are also called as Ragged arrays.

Consider an example of a 2-D array with 2 rows, here each row can have a different number
of columns, i.e, elements. They don't need to be equal in length.

It is important to understand that 2-D arrays have the same number of columns in each
row. Whereas in jagged arrays, the rows have different numbers of columns.

Declaration and Initialisation of Jagged Array


The most common way to declare and initialize a jagged array is as follows –

Syntax
In order to declare a jagged array, we need to write its name preceded by its data type. The
new keyword is used to create the object. Then we specify the number of rows and leave
the column empty.

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


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

There are other ways to declare and initialize jagged arrays. Let us take a look at the other
ways.

Example
int arr[][] = new int[][]
{
new int[] { 1, 2, 3, 4 },
new int[] { 4, 5},
new int[] { 6, 7, 8},
};

Another way to declare and initialize a jagged array can be omitting the first new keyword.

int arr[][] ={
new int[] { 1, 2, 3, 4 },
new int[] { 4, 5},
new int[] { 6, 7, 8},

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 8


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

};

Apart from the above methods, we can omit all the new keywords and initialize the value
inside a jagged array.

int arr[][] ={
{ 1, 2, 3, 4 },
{ 4, 5},
{ 6, 7, 8},
};

Pictorial Representation of Jagged Array in Memory


Consider the jagged array,

int[][] Jagged_arr = {
{ 99, 18, 1, 77 },
{ 43, 8 },
{ 17,101,2 } };

So, this array has 3 rows, and each row has a variable number of columns. They can be
visualized in the following way.

The jagged array is stored in heap memory and each individual element of this jagged array
is a one-dimensional array. Each 1-D array has a different size. This is what a jagged array
is.

Read and Store Elements in a Dynamic Sized Jagged Array

Let us look at an example where we will create a 2-D jagged array. Here the zeroth row has
1 element, the first row has 2 elements, so on such that the nth row has n+1 elements.

We will do this by using a for loop. Hence a new array with the given size will be created.

import [Link].*;
import [Link].*;
public class Main
{
public static void main(String[] args)
{
Scanner scn=new Scanner([Link]);

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 9


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

//Taking the input from user


int r = [Link]();

// Declaring jagged array with r rows


int arr[][] = new int[r][];

//We are creating a jagged array where the 0th row has 1 element,
//1st row has 2 elements
//such that nth row has n+1 elements
for (int i = 0; i < [Link]; i++)
arr[i] = new int[i + 1];

// Initializing array
int temp = 0;
for (int i = 0; i < [Link]; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = temp++;

// Displaying the elements of 2-D Jagged array


[Link]("Elements of 2-D Jagged Array for n= " + r);
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
Output
Elements of 2-D Jagged Array for n= 9
0
12
345
6789
10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44

Jagged Array Example


In the previous section, we saw an example of a dynamic-sized jagged array. Now we will
use another method to create a jagged array and print its elements.

import [Link].*;
import [Link].*;
public class Main
{

public static void main(String[] args)


{

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 10


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

// Declaring a 2-D array with 3 rows


int arr[][] = new int[3][];
// create a jagged array
arr[0] = new int[]{99,100,101};
arr[1] = new int[]{199,200};
arr[2] = new int[]{299,300,301,302,303};

// Displaying the elements of 2-D Jagged array


[Link]("Elements of 2-D Jagged Array");
for (int i = 0; i < [Link]; i++)
{
for (int j = 0; j < arr[i].length; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
Output
Elements of 2-D Jagged Array
99 100 101
199 200
299 300 301 302 303

String Handling in Java:

Strings in Java:
In Java, the String class is used to represent sequences of characters. Strings are one of the
most commonly used data types in Java and are essential for handling textual data. Unlike
primitive data types (like int, float, etc.), String is an object that comes with a variety of
methods for manipulating and querying strings.

Characteristics of Strings

• Immutable: Strings in Java are immutable, which means once a String object is created,
it cannot be changed. Any operation that modifies a string results in the creation of a
new String object.
• String Pool: Java optimizes memory usage for strings by maintaining a pool of string
literals. When a string is created using a literal, the JVM checks the string pool first. If
the string already exists, it returns the reference; otherwise, it creates a new string in
the pool.

Creating Strings

There are several ways to create strings in Java:

Using String Literals

String str1 = "Hello, World!";

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 11


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

When a string is created using a literal, it is stored in the string pool.

Using the new Keyword

String str2 = new String("Hello, World!");

This explicitly creates a new String object, even if the same string exists in the string
pool.

Methods in String class

Java's String class provides a wide range of methods for manipulating strings. Here are
some of the most commonly used methods:

length()
Returns the length of the string (i.e., the number of characters).
int len = [Link](); // len is 13

charAt(int index)
Returns the character at the specified index (0-based index).

char ch = [Link](0); // ch is 'H'

substring(int beginIndex)
Returns a substring starting from the specified index to the end of the string.

String subStr = [Link](7); // subStr is "World!"

substring(int beginIndex, int endIndex)


Returns a substring from beginIndex to endIndex - 1.

String subStr = [Link](7, 12); // subStr is "World"

equals(Object another)
Compares two strings for content equality (case-sensitive).

boolean isEqual = [Link]("Hello, World!"); // isEqual is true

equalsIgnoreCase(String another)
Compares two strings, ignoring case differences.

boolean isEqual = [Link]("hello, world!"); // isEqual is true

compareTo(String another)
Compares two strings lexicographically.
• Returns 0 if the strings are equal.
• Returns a negative number if the current string is lexicographically less than the
other string.
• Returns a positive number if the current string is greater.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 12


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

int result = [Link]("Hello, Java!"); // result depends on the comparison

toUpperCase()
Converts all characters in the string to uppercase.

String upperStr = [Link](); // upperStr is "HELLO, WORLD!"

toLowerCase()
Converts all characters in the string to lowercase.

String lowerStr = [Link](); // lowerStr is "hello, world!"


trim()
Removes leading and trailing whitespace from the string.

String trimmedStr = [Link](); // trimmedStr is "Hello, World!"

replace(char oldChar, char newChar)


Replaces all occurrences of the specified character with a new character.

String replacedStr = [Link]('o', 'a'); // replacedStr is "Hella, Warld!"

split(String regex)
Splits the string based on the specified regular expression and returns an array of
substrings.

String[] words = [Link](", "); // words is ["Hello", "World!"]

concat(String str)
Concatenates the specified string to the end of the current string.

String newStr = [Link](“ How are you?”); // newStr is “Hello, World! How are you?”

String Constant Pool

The String Constant Pool (also known as the String Intern Pool) is a special memory region
in Java where String literals are stored. This optimization feature helps save memory and
improve performance when handling strings.

How the String Constant Pool Works:

1. String Literals:
• When you create a string using a literal, like "Hello", Java checks the String
Constant Pool to see if an identical string already exists.
• If it does, Java returns a reference to the existing string in the pool instead of
creating a new object.
• If the string does not exist in the pool, Java adds it to the pool and then returns a
reference to it.

String str1 = "Hello"; // This creates a string literal "Hello" and stores it in the pool.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 13


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

String str2 = "Hello"; // This does not create a new string; str2 points to the same
"Hello" in the pool.

In the example above, both str1 and str2 refer to the same object in the String Constant
Pool. Thus, str1 == str2 would return true.

2. String Objects Created Using new:


• When you create a string with the new keyword, a new String object is created
on the heap, and it does not check the pool.
• Even if the string value is the same as a literal or another string object, it will not
refer to the pool.

String str3 = new String("Hello"); // Creates a new String object in the heap.

In this case, str3 does not refer to the string in the String Constant Pool but rather a separate
String object in the heap. Therefore, str3 == str1 would return false, but [Link](str1)
would return true.

3. Interning Strings:
• The intern() method can be used on a string object to add it to the String Constant
Pool or get its reference if it already exists in the pool.

String str4 = new String("Hello").intern(); // Forces str4 to refer to the "Hello" in the
pool.

After calling intern(), str4 now refers to the pooled string, so str4 == str1 would return true.

Why Use the String Constant Pool?

1. Memory Efficiency:
• By reusing immutable string objects, the String Constant Pool reduces the
number of strings in memory, thus saving space.
2. Performance Improvement:
• Since strings are frequently used in Java applications, having a shared pool can
reduce the overhead of creating and garbage collecting string objects.

Example:

public class StringPoolExample


{
public static void main(String[] args)
{
String s1 = "Java"; // "Java" is added to the String Constant Pool.
String s2 = "Java"; // No new object is created; s2 points to the same "Java" in the
pool.
[Link](s1 == s2); // true
String s3 = new String("Java"); // A new String object in the heap.
[Link](s1 == s3); // false
[Link]([Link](s3)); // true
String s4 = [Link](); // s4 now points to the "Java" in the pool.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 14


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

[Link](s1 == s4); // true


}
}
OUTPUT:
true
false
true
true

Important Points:

• The String Constant Pool is part of the Java Heap memory.


• Strings in the pool are immutable and shared, making Java string handling more
efficient.
• Explicitly using new String("...") creates a new object and does not use the pool
unless intern() is called.
• String interning helps in optimizing memory usage and can be used when string
references are frequently compared.

String Buffer class

Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Constructors of String Buffer Class:

Constructor Description
StringBuffer() It creates an empty String buffer with the initial
capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified
capacity as length.

methods of String Buffer class:

Modifier and Type Method Description


public synchronized append(String s) It is used to append the specified
StringBuffer string with this string. The append()
method is overloaded like
append(char), append(boolean),
append(int), append(float),
append(double) etc.
public synchronized insert(int offset, String It is used to insert the specified string
StringBuffer s) with this string at the specified
position. The insert() method is

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 15


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

overloaded like insert(int, char),


insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double)
etc.
public synchronized replace(int startIndex, It is used to replace the string from
StringBuffer int endIndex, String str) specified startIndex and endIndex.
public synchronized delete(int startIndex, int It is used to delete the string from
StringBuffer endIndex) specified startIndex and endIndex.
public synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() It is used to return the current
capacity.
public void ensureCapacity(int It is used to ensure the capacity at
minimumCapacity) least equal to the given minimum.
public char charAt(int index) It is used to return the character at
the specified position.
public int length() It is used to return the length of the
string i.e. total number of characters.
public String substring(int It is used to return the substring from
beginIndex) the specified beginIndex.
public String substring(int It is used to return the substring from
beginIndex, int the specified beginIndex and
endIndex) endIndex.

What is a mutable String?

A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.

1) StringBuffer Class append() Method

The append() method concatenates the given argument with this String.

class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}

Output:
Hello Java

2) StringBuffer insert() Method

The insert() method inserts the given String with this string at the given position.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 16


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}
Output:
HJavaello

3) StringBuffer replace() Method

The replace() method replaces the given String from the specified beginIndex and
endIndex.

class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
Output:
HJavalo

4) StringBuffer delete() Method

The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex-1.

class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}
Output:
Hlo

5) StringBuffer reverse() Method

The reverse() method of the StringBuilder class reverses the current String.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 17


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);//prints olleH
}
}
Output:
olleH

6) StringBuffer capacity() Method

The capacity() method of the StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.

class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 18


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}
Output:
16
16
34
34
70

Difference between String and StringBuffer

No. String StringBuffer


1) The String class is immutable. The StringBuffer class is mutable.
2) String is slow and consumes more memory StringBuffer is fast and consumes
when we concatenate too many strings less memory when we
because every time it creates new instance. concatenate t strings.
3) String class overrides the equals() method StringBuffer class doesn't
of Object class. So you can compare the override the equals() method of
contents of two strings by equals() method. Object class.
4) String class is slower while performing StringBuffer class is faster while
concatenation operation. performing concatenation
operation.
5) String class uses String constant pool. StringBuffer uses Heap memory

Wrapper classes

In Java, wrapper classes provide a way to use primitive data types (like int, char, boolean,
etc.) as objects. Each primitive type has a corresponding wrapper class:

• byte -> Byte


• short -> Short
• int -> Integer
• long -> Long
• float -> Float
• double -> Double
• char -> Character
• boolean -> Boolean

Key Features of Wrapper Classes:

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 19


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

1. Object Representation of Primitives: Wrapper classes encapsulate primitive


types within an object, allowing primitives to be used where objects are required,
such as in collections like ArrayList.
2. Immutability: Instances of wrapper classes are immutable. Once a wrapper object
is created, its value cannot be changed.
3. Utility Methods: Wrapper classes provide methods for converting between
different data types, parsing strings, and more. For example:
o [Link](String s): Converts a string to an int.
o [Link](String s): Converts a string to a Double object.
4. Autoboxing and Unboxing: Java automatically converts between primitives and
their corresponding wrapper classes when needed:
o Autoboxing: Automatically converting a primitive to a corresponding
wrapper class object. For example, int to Integer.
o Unboxing: Automatically converting a wrapper class object to a
corresponding primitive. For example, Integer to int.

Example Usage:

public class WrapperExample


{
public static void main(String[] args)
{
// Autoboxing: primitive to wrapper
Integer num = 5; // int 5 is converted to Integer object

// Unboxing: wrapper to primitive


int primitiveNum = num; // Integer object num is converted to int

// Using utility methods


String str = "123";
int parsedInt = [Link](str); // Converts string to int

[Link]("Autoboxed Integer: " + num);


[Link]("Unboxed primitive: " + primitiveNum);
[Link]("Parsed integer from String: " + parsedInt);
}
}
In this example:
• num demonstrates autoboxing.
• primitiveNum shows unboxing.
• [Link] is a utility method for converting a string to an int.

Type Conversion

Type conversion in Java refers to the process of converting a value from one data type to
another. Java supports two main types of conversions: implicit (automatic) type conversion
and explicit (manual) type conversion, also known as casting.

1. Implicit Type Conversion (Widening Conversion)

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 20


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

Implicit type conversion, also known as widening conversion, happens automatically


when a smaller data type is converted to a larger data type. This type of conversion
does not result in data loss because the target type can accommodate all the values of
the source type.

Examples of Widening Conversion:


• byte -> short -> int -> long -> float -> double
• char -> int

Example:

public class ImplicitConversionExample


{
public static void main(String[] args)
{
int num = 100;
double doubleNum = num; // int to double conversion (implicit)

[Link]("Integer value: " + num); // Output: Integer value: 100


[Link]("Double value: " + doubleNum); // Output: Double value: 100.0
}
}

In this example, an int value 100 is implicitly converted to a double because double is
a larger data type than int.

2. Explicit Type Conversion (Narrowing Conversion)


Explicit type conversion, also known as narrowing conversion or casting, is required
when converting a larger data type to a smaller data type. This type of conversion can
lead to data loss because the target type may not be able to accommodate all possible
values of the source type.
To perform a narrowing conversion, you must explicitly cast the value to the desired
type using parentheses.

Examples of Narrowing Conversion:


• double -> float -> long -> int -> short -> byte
• int -> char

Example:

public class ExplicitConversionExample


{
public static void main(String[] args)
{
double doubleNum = 100.99;
int num = (int) doubleNum; // double to int conversion (explicit)

[Link]("Double value: " + doubleNum); // Output: Double value:


100.99
[Link]("Integer value: " + num); // Output: Integer value: 100

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 21


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

}
}

In this example, a double value 100.99 is explicitly converted to an int. This conversion
truncates the decimal part, resulting in a loss of data.

3. Type Conversion Between String and Other Types


Java provides methods to convert strings to other data types and vice versa.

Converting from String to Primitive Types:


• [Link](String s): Converts a string to an int.
• [Link](String s): Converts a string to a double.
• [Link](String s): Converts a string to a boolean.

Example:
public class StringToPrimitiveExample
{
public static void main(String[] args)
{
String strInt = "100";
String strDouble = "10.5";
String strBoolean = "true";

int num = [Link](strInt);


double doubleNum = [Link](strDouble);
boolean boolValue = [Link](strBoolean);

[Link]("Parsed int: " + num); // Output: Parsed int: 100


[Link]("Parsed double: " + doubleNum); // Output: Parsed double:
10.5
[Link]("Parsed boolean: " + boolValue);// Output: Parsed boolean:
true
}
}

Converting from Primitive Types to String:


• [Link](int i): Converts an int to a string.
• [Link](double d): Converts a double to a string.
• [Link](boolean b): Converts a boolean to a string.

Example:
public class PrimitiveToStringExample
{
public static void main(String[] args)
{
int num = 100;
double doubleNum = 10.5;
boolean boolValue = true;

String strInt = [Link](num);

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 22


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

String strDouble = [Link](doubleNum);


String strBoolean = [Link](boolValue);

[Link]("String from int: " + strInt); // Output: String from int: 100
[Link]("String from double: " + strDouble); // Output: String from
double: 10.5
[Link]("String from boolean: " + strBoolean);// Output: String from
boolean: true
}
}

Collections in Java:

The Collections in Java is a framework that provides an architecture to store and


manipulate the group of objects.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet).

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

What is a framework in Java


• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.

What is Collections framework


The Collections framework represents a unified architecture for storing and manipulating
a group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm

Interfaces: The main interfaces that define different types of collections are:

• Collection: The root interface for most of the collection classes.


o List: An ordered collection (like an array but resizable). Example
implementations: ArrayList, LinkedList.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 23


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

o Set: A collection that doesn't allow duplicate elements. Example


implementations: HashSet, LinkedHashSet, TreeSet.
o Queue: A collection designed for holding elements prior to processing.
Example implementations: PriorityQueue, LinkedList (also implements
Queue).
o Deque: A double-ended queue allowing elements to be inserted or removed
from both ends. Example: ArrayDeque.

• Map: Not a true collection but a framework part. It maps keys to values, with unique
keys. Example implementations: HashMap, TreeMap, LinkedHashMap.

Classes (Implementations): These are concrete implementations of the interfaces:


• ArrayList: Resizable array that implements List.
• LinkedList: Doubly-linked list that implements both List and Queue.
• HashSet: Implements Set, backed by a hash table.
• TreeSet: Implements Set, where elements are ordered.
• HashMap: Implements Map, backed by a hash table.
• LinkedHashMap: Ordered version of HashMap.
• TreeMap: Implements Map, where keys are sorted.

Algorithms: The framework provides several utility methods for working with collections,
such as sorting, searching, and shuffling. These are available through the Collections class.

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The [Link] package contains all the
classes and interfaces for the Collection framework.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 24


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

Hierarchy of Map Framework

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

No. Method Description


1 public boolean It returns true if the iterator has more elements
hasNext() otherwise it returns false.
2 public Object next() It returns the element and moves the cursor pointer
to the next element.
3 public void remove() It removes the last elements returned by the
iterator. It is less used.

Iterable Interface

The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collections framework. It declares the methods that every collection will have. In other

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 25


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

words, we can say that the Collection interface builds the foundation on which the
collections framework depends.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :


1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 26


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

3. List <data-type> list3 = new Vector();


4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.

One of the class that implement the List interface are ArrayList.

ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but
there is no size limit. We can add or remove elements anytime. So, it is much more flexible
than the traditional array. It is found in the [Link] package. The elements of ArrayList are
organized as an array internally. The default size of an ArrayList is 10.

The ArrayList in Java can have the duplicate elements also. It implements the List interface
so we can use all the methods of the List interface here. The ArrayList maintains the
insertion order internally. The elements stored in the ArrayList class can be randomly
accessed.

We cannot create an array list of the primitive types, such as int, float, char, etc. It is required
to use the required wrapper class in such cases.

The ArrayList class has the following constructors.


• ArrayList( ) - Creates an empty ArrayList.
• ArrayList(Collection c) - Creates an ArrayList with given collection of elements.
• ArrayList(int size) - Creates an empty ArrayList with given size (capacity).

ArrayList class declaration

The ArrayList class has the following declaration.

ArrayList<int> al = ArrayList<int>(); // does not work


ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

Key Points:
• The ArrayList is a child class of AbstractList
• The ArrayList implements interfaces like List, Serializable, Cloneable,
and RandomAccess.
• The ArrayList allows to store duplicate data values.
• The ArrayList allows to access elements randomly using index-based accessing.
• The ArrayList maintains the order of insertion.

Consider the following example.

import [Link].*;
class TestJavaCollection1
{
public static void main(String args[])
{

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 27


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

ArrayList<String> list=new ArrayList<String>();//Creating arraylist


[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay

Method Description

The following table providess a consolidated view of all methods of ArrayList.


Method Description
boolean add(E element) Appends given element to the ArrayList.
boolean addAll(Collection c) Appends given collection of elements to the ArrayList.
void add(int index, E element) Inserts the given element at specified index.
boolean addAll(int index, Inserts the given collection of elements at specified
Collection c) index.
E get(int index) Returns element at specified index from the ArrayList.
ArrayList subList(int Returns an ArrayList that contails elements from
startIndex, int lastIndex) specified startIndex to lastIndex-1 from the invoking
ArrayList.
int indexOf(E element) Returns the index value of given element first
occurence in the ArrayList.
int lastIndexOf(E element) Returns the index value of given element last occurence
in the ArrayList.
E set(int index, E newElement) Replace the element at specified index with
newElement in the invoking ArrayList.
ArrayList Replaces each element of invoking ArrayList with the
replaceAll(UnaryOperator e) result of applying the operator to that element.
E remove(int index) Removes the element at specified index in the invoking
ArrayList.
boolean remove(Object Removes the first occurence of the given element from
element) the invoking ArrayList.
boolean removeAll(Collection Removes the given collection of elements from the
c) invoking ArrayList.
void retainAll(Collection c) Removes all the elements except the given collection of
elements from the invoking ArrayList.
boolean removeIf(Predicate Removes all the elements from the ArrayList that
filter) satisfies the given predicate.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 28


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

void clear( ) Removes all the elements from the ArrayList.


int size( ) Returns the total number of elements in the invoking
ArrayList.
boolean isEmpty( ) Returns true if the list is empty otherwise returns false.
boolean contains(Object Returns true if the list contains given element
element) otherwise returns false.
void sort(Comparator c) Sorts all the elements of invoking list based on the given
comparator.
Object clone( ) Returns a shallow copy of an ArrayList.
Object[ ] toArray( ) Returns an array of Object instances that contains all
the elements from invoking ArrayList.
Spliterator spliterator( ) Creates spliterator over the elements in a list.
void trimToSize( ) Used to trim a ArrayList instance to the number of
elements it contains.

Example:

import [Link].*;

public class ArrayListMethodsDemo


{
public static void main(String[] args)
{
// Create an ArrayList
ArrayList<String> list = new ArrayList<>();

// 1. add(E element)
[Link]("Apple");
[Link]("Banana");
[Link]("After add(): " + list);

// 2. addAll(Collection c)
ArrayList<String> newItems = new ArrayList<>([Link]("Cherry", "Dates"));
[Link](newItems);
[Link]("After addAll(): " + list);

// 3. add(int index, E element)


[Link](1, "Blueberry");
[Link]("After add(int index, E element): " + list);

// 4. addAll(int index, Collection c)


ArrayList<String> moreItems = new ArrayList<>([Link]("Orange",
"Grapes"));
[Link](2, moreItems);
[Link]("After addAll(int index, Collection c): " + list);

// 5. get(int index)
[Link]("Element at index 2: " + [Link](2));

// 6. subList(int startIndex, int endIndex)

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 29


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

ArrayList<String> subList = new ArrayList<>([Link](1, 4));


[Link]("SubList (1, 4): " + subList);

// 7. indexOf(E element)
[Link]("Index of 'Banana': " + [Link]("Banana"));

// 8. lastIndexOf(E element)
[Link]("Apple");
[Link]("Last index of 'Apple': " + [Link]("Apple"));

// 9. set(int index, E newElement)


[Link](1, "Blackberry");
[Link]("After set(1, 'Blackberry'): " + list);

// 10. replaceAll(UnaryOperator e)
[Link](String::toUpperCase);
[Link]("After replaceAll(toUpperCase): " + list);

// 11. remove(int index)


[Link](2);
[Link]("After remove(2): " + list);

// 12. remove(Object element)


[Link]("APPLE");
[Link]("After remove('APPLE'): " + list);

// 13. removeAll(Collection c)
ArrayList<String> removeItems = new ArrayList<>([Link]("DATES",
"GRAPES"));
[Link](removeItems);
[Link]("After removeAll(): " + list);

// 14. retainAll(Collection c)
ArrayList<String> retainItems = new ArrayList<>([Link]("BANANA",
"BLACKBERRY"));
[Link](retainItems);
[Link]("After retainAll(): " + list);

// 15. removeIf(Predicate filter)


[Link](s -> [Link]("B"));
[Link]("After removeIf(starts with 'B'): " + list);

// 16. clear()
[Link]();
[Link]("After clear(): " + list);

// Re-populate for further methods


[Link]([Link]("Apple","Cherry","Banana"));
[Link]("After adding the list is: " + list);

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 30


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

// 17. size()
[Link]("Size of list: " + [Link]());

// 18. isEmpty()
[Link]("Is list empty? " + [Link]());

// 19. contains(Object element)


[Link]("Does list contain 'Banana'? " + [Link]("Banana"));

// 20. sort(Comparator c)
[Link]([Link]());
[Link]("After sort(): " + list);

// 21. clone()
ArrayList<String> clonedList = (ArrayList<String>) [Link]();
[Link]("Cloned list: " + clonedList);

// 22. toArray()
Object[] array = [Link]();
[Link]("Array from list: " + [Link](array));

// 23. spliterator()
[Link]().forEachRemaining([Link]::println);

// 24. trimToSize()
[Link]();
[Link]("After trimToSize(): " + list);
}
}

Output:
After add(): [Apple, Banana]
After addAll(): [Apple, Banana, Cherry, Dates]
After add(int index, E element): [Apple, Blueberry, Banana, Cherry, Dates]
After addAll(int index, Collection c): [Apple, Blueberry, Orange, Grapes, Banana,
Cherry, Dates]
Element at index 2: Orange
SubList (1, 4): [Blueberry, Orange, Grapes]
Index of 'Banana': 4
Last index of 'Apple': 7
After set(1, 'Blackberry'): [Apple, Blackberry, Orange, Grapes, Banana, Cherry, Dates,
Apple]
After replaceAll(toUpperCase): [APPLE, BLACKBERRY, ORANGE, GRAPES, BANANA,
CHERRY, DATES, APPLE]
After remove(2): [APPLE, BLACKBERRY, GRAPES, BANANA, CHERRY, DATES, APPLE]
After remove('APPLE'): [BLACKBERRY, GRAPES, BANANA, CHERRY, DATES, APPLE]
After removeAll(): [BLACKBERRY, BANANA, CHERRY, APPLE]
After retainAll(): [BLACKBERRY, BANANA]
After removeIf(starts with 'B'): []

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 31


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

After clear(): []
After adding the list is: [Apple, Cherry, Banana]
Size of list: 3
Is list empty? false
Does list contain 'Banana'? true
After sort(): [Apple, Banana, Cherry]
Cloned list: [Apple, Banana, Cherry]
Array from list: [Apple, Banana, Cherry]
Apple
Banana
Cherry
After trimToSize(): [Apple, Banana, Cherry]

HashSet

The HashSet class is a part of java collection framework. It is available inside


the [Link] package. The HashSet class extends AbstractSet class and
implements Set interface.

The elements of HashSet are organized using a mechanism called hashing. The HashSet is
used to create hash table for storing set of elements.

The HashSet class is used to create a collection that uses a hash table for storing set of
elements.
• The HashSet is a child class of AbstractSet
• The HashSet implements interfaces like Set, Cloneable, and Serializable.
• The HashSet does not allows to store duplicate data values, but null values are
allowed.
• The HashSet does not maintains the order of insertion.
• The HashSet initial capacity is 16 elements.
• The HashSet is best suitable for search operations.

HashSet class constructors


The HashSet class has the following constructors.

• HashSet( ) - Creates an empty HashSet with the default initial capacity (16).
• HashSet(Collection c) - Creates a HashSet with given collection of elements.
• HashSet(int initialCapacity) - Creates an empty HashSet with the specified initial
capacity.
• HashSet(int initialCapacity, float loadFactor) - Creates an empty HashSet with the

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 32


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

specified initial capacity and loadFactor.

HashSet class declaration

The HashSet class has the following declaration.

Example

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

HashSet Class Methods:

SN Modifier & Type Method Description

1) boolean add(E e) It is used to add the specified element to


this set if it is not already present.
2) void clear() It is used to remove all of the elements
from the set.
3) object clone() It is used to return a shallow copy of this
HashSet instance: the elements
themselves are not cloned.
4) boolean contains(Object o) It is used to return true if this set contains
the specified element.
5) boolean isEmpty() It is used to return true if this set contains
no elements.
6) Iterator<E> iterator() It is used to return an iterator over the
elements in this set.
7) boolean remove(Object o) It is used to remove the specified element
from this set if it is present.
8) int size() It is used to return the number of
elements in the set.
9) Spliterator<E> spliterator() It is used to create a late-binding and fail-
fast Spliterator over the elements in the
set.

Example:
import [Link].*;

public class HashSetMethodsDemo


{
public static void main(String[] args)
{
// 1. add(E e) - Add elements to HashSet
HashSet<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Banana"); // Duplicate, won't be added
[Link]("After add(): " + set);

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 33


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

// 2. clear() - Remove all elements from HashSet


HashSet<String> anotherSet = new HashSet<>(set);
[Link]();
[Link]("After clear(): " + anotherSet);

// 3. clone() - Shallow copy of the HashSet


HashSet<String> clonedSet = (HashSet<String>) [Link]();
[Link]("Cloned HashSet: " + clonedSet);

// 4. contains(Object o) - Check if an element is present


[Link]("Does set contain 'Apple'? " + [Link]("Apple"));

// 5. isEmpty() - Check if the set is empty


[Link]("Is the set empty? " + [Link]());

// 6. iterator() - Iterate over elements


Iterator<String> iterator = [Link]();
[Link]("Elements using iterator(): ");
while ([Link]())
{
[Link]([Link]() + " ");
}
[Link]();

// 7. remove(Object o) - Remove an element


[Link]("Banana");
[Link]("After remove('Banana'): " + set);

// 8. size() - Get the number of elements


[Link]("Size of the set: " + [Link]());

// 9. spliterator() - Create a spliterator for the set


Spliterator<String> spliterator = [Link]();
[Link]("Spliterator elements: ");
[Link]([Link]::println);
}
}

Output:
After add(): [Apple, Cherry, Banana]
After clear(): []
Cloned HashSet: [Cherry, Apple, Banana]
Does set contain 'Apple'? true
Is the set empty? false
Elements using iterator(): Apple Cherry Banana
After remove('Banana'): [Apple, Cherry]
Size of the set: 2
Spliterator elements:
Apple
Cherry

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 34


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

HashMap
HashMap class implements the Map interface which allows us to store key and value pair,
where keys should be unique. If you try to insert the duplicate key, it will replace the
element of the corresponding key. It is easy to perform operations using the key index like
updation, deletion, etc. HashMap class is found in the [Link] package. It inherits the
AbstractMap class and implements the Map interface.

HashMap class declaration


Let's see the declaration for [Link] class.

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable,


Serializable

HashMap class Parameters


Let's see the Parameters for [Link] class.

• K: It is the type of keys maintained by this map.


• V: It is the type of mapped values.

Constructors of Java HashMap class

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map<? extends K,? extends It is used to initialize the hash map by using the
V> m) elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash
map to the given integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load
loadFactor) factor of the hash map by using its arguments.

Methods of Java HashMap class

Method Description
void clear() It is used to remove all of the mappings
from this map.
boolean isEmpty() It is used to return true if this map contains

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 35


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

no key-value mappings.
Object clone() It is used to return a shallow copy of this
HashMap instance: the keys and values
themselves are not cloned.
Set entrySet() It is used to return a collection view of the
mappings contained in this map.
Set keySet() It is used to return a set view of the keys
contained in this map.
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the
map.
V putIfAbsent(K key, V value) It inserts the specified value with the
specified key in the map only if it is not
already specified.
V remove(Object key) It is used to delete an entry for the specified
key.
boolean remove(Object key, Object value) It removes the specified values with the
associated specified keys from the map.
V compute(K key, BiFunction<? super K,? It is used to compute a mapping for the
super V,? extends V> remappingFunction) specified key and its current mapped value
(or null if there is no current mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the
super K,? extends V> mappingFunction) given mapping function, if the specified key
is not already associated with a value (or is
mapped to null), and enters it into this map
unless null.
V computeIfPresent(K key, BiFunction<? It is used to compute a new mapping given
super K,? super V,? extends V> the key and its current mapped value if the
remappingFunction) value for the specified key is present and
non-null.
boolean containsValue(Object value) This method returns true if some value
equal to the value exists within the map,
else return false.
boolean containsKey(Object key) This method returns true if some key equal
to the key exists within the map, else return
false.
boolean equals(Object o) It is used to compare the specified Object
with the Map.
void forEach(BiConsumer<? super K,? It performs the given action for each entry
super V> action) in the map until all entries have been
processed or the action throws an
exception.
V get(Object key) This method returns the object that
contains the value associated with the key.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified
key is mapped, or defaultValue if the map
contains no mapping for the key.
boolean isEmpty() This method returns true if the map is
empty; returns false if it contains at least
one key.

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 36


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

V merge(K key, V value, BiFunction<? super


If the specified key is not already associated
V,? super V,? extends V>
with a value or is associated with null,
remappingFunction) associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value for a
specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value
newValue) for a specified key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the
super V,? extends V> function) result of invoking the given function on that
entry until all entries have been processed
or the function throws an exception.
Collection<V> values() It returns a collection view of the values
contained in the map.
int size() This method returns the number of entries
in the map.

Example:
import [Link].*;

public class HashMapExample


{
public static void main(String[] args)
{
// Creating a HashMap
HashMap<Integer, String> studentMap = new HashMap<>();

// 1. Adding elements using put() method


[Link](1, "John");
[Link](2, "Alice");
[Link](3, "Bob");
[Link](4, "Emma");

// Displaying the HashMap


[Link]("Initial HashMap: " + studentMap);

// 2. Accessing an element using get() method


String student = [Link](2); // gets the value for key 2
[Link]("Student with ID 2: " + student);

// 3. Checking if a key or value exists using containsKey() and containsValue()


boolean hasKey = [Link](3); // checks if key 3 exists
boolean hasValue = [Link]("Emma"); // checks if value
"Emma" exists
[Link]("Has key 3: " + hasKey);
[Link]("Has value 'Emma': " + hasValue);

// 4. Removing an element using remove() method


[Link](1); // removes the entry with key 1
[Link]("HashMap after removal: " + studentMap);

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 37


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram&[Link]

// 5. Iterating through the HashMap using keySet() and values()


[Link]("Keys in HashMap: " + [Link]());
[Link]("Values in HashMap: " + [Link]());

// 6. Replacing a value using replace() method


[Link](3, "Charlie"); // replaces the value for key 3
[Link]("HashMap after replacing value for key 3: " +
studentMap);

// 7. Size of the HashMap using size() method


int size = [Link]();
[Link]("Size of the HashMap: " + size);

// 8. Clearing the HashMap using clear() method


[Link](); // removes all entries
[Link]("HashMap after clearing: " + studentMap);
}
}

Output:
Initial HashMap: {1=John, 2=Alice, 3=Bob, 4=Emma}
Student with ID 2: Alice
Has key 3: true
Has value 'Emma': true
HashMap after removal: {2=Alice, 3=Bob, 4=Emma}
Keys in HashMap: [2, 3, 4]
Values in HashMap: [Alice, Bob, Emma]
HashMap after replacing value for key 3: {2=Alice, 3=Charlie, 4=Emma}
Size of the HashMap: 3
HashMap after clearing: {}
************

AIM & CIC Sagi Rama Krishnam Raju Engineering College(A) 38

You might also like