0% found this document useful (0 votes)
18 views203 pages

D2 JDK Jre JVM

Uploaded by

S Naveen Kumar
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)
18 views203 pages

D2 JDK Jre JVM

Uploaded by

S Naveen Kumar
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/ 203

Is Java compiled or Interpreted ?

Is .............
How
?????
• Java is compiled and interpreted language which is done in two steps.
• Java and the JVM were designed with portability in mind.
• The javac command-line tool compiles Java source code into Java
class files containing platform-neutral bytecode.
• The compiled class files (bytecode) can be executed by the Java Virtual
Machine (JVM).
• JDK stands for Java Development kit.
• It includes JRE and other development tools.
• Tools like java compiler(javac), javadoc generator.
• JRE stands for Java Runtime Environment.
• It is the implementation of JVM.
• It includes java run time libraries and .class files.
• JVM stands for Java Virtual Machine.
• It is called a virtual machine because it doesn't
physically exist.
• It will execute the java byte code line by line.

JVM CLASS LOADER

EXECUTION ENGINEE
JVM Architecture
Structure of Java
package packagename;

import packagename;

class classname{

variables;

methods/constructors;

main method(){

// executing code .

}
package statement
• In real time we create packages for better code segregation.
• package statement is completely optional(Mandatory for real time projects).
• If we are writing a package it should be the first line.
• Maximum one package statement can write.
Import statement
• To import existing and user defined packages.
• Importing is also completely optional.
• If we are writing an import statement after package and before class declaration.
• We can write any number of imports.
Java Class
??
Main method in Java
• Can write any number of statements.
• But each statement should be terminated with ;(semicolon) j
• java is case sensitive.
• If no main method, code compiles but run time error occurs.
• we can overload main method(Will be discussed in OOPS).
Code Comments
Single line comment - //

Multi line Comment


public void connectToDB() {
/*
* BusinessLogic bl = new BusinessLogic(); bl.connectToFTP();
Logics lg=new
* Logics();
*/
}
Types of Operator in Java
1)Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators & Terinary

1) Basic Arithmetic Operators


Basic arithmetic operators are: +, -, *, /, %
+ is for addition.

– is for subtraction.

* is for multiplication.

/ is for division.

% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0

Example of Arithmetic Operators


public class ArithmeticOperatorDemo {
public static void main(String args[]) {
int num1 = 100;
int num2 = 20;

System.out.println("num1 + num2: " + (num1 + num2) );


System.out.println("num1 - num2: " + (num1 - num2) );
System.out.println("num1 * num2: " + (num1 * num2) );
System.out.println("num1 / num2: " + (num1 / num2) );
System.out.println("num1 % num2: " + (num1 % num2) );
}
}

2) Assignment Operators
Assignments operators in java are: =, +=, -=, *=, /=, %=
num2 = num1 would assign value of variable num1 to the variable.
num2+=num1 is equal to num2 = num2+num1

num2-=num1 is equal to num2 = num2-num1

num2*=num1 is equal to num2 = num2*num1

num2/=num1 is equal to num2 = num2/num1

num2%=num1 is equal to num2 = num2%num1

public class AssignmentOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
System.out.println("= Output: "+num2);

num2 += num1;
System.out.println("+= Output: "+num2);

num2 -= num1;
System.out.println("-= Output: "+num2);

num2 *= num1;
System.out.println("*= Output: "+num2);

num2 /= num1;
System.out.println("/= Output: "+num2);

num2 %= num1;
System.out.println("%= Output: "+num2);
}
}

3) Auto-increment and Auto-decrement


Operators
++ and —
num++ is equivalent to num=num+1;

num–- is equivalent to num=num-1;


4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in
conditional statements and loops for evaluating a condition.

Logical operators in java are: &&, ||, !

Let’s say we have two boolean variables b1 and b2.

b1&&b2 will return true if both b1 and b2 are true else it would return false.

b1||b2 will return false if both b1 and b2 are false else it would return true.

!b1 would return the opposite of b1, that means it would be true if b1 is false
and it would return false if b1 is true..

Example of Logical Operators


public class LogicalOperatorDemo {
public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;

System.out.println("b1 && b2: " + (b1&&b2));


System.out.println("b1 || b2: " + (b1||b2));
System.out.println("!(b1 && b2): " + !(b1&&b2));
}
}

5) Comparison(Relational) operators
We have six relational operators in Java: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal

!= returns true if left side is not equal to the right side of operator.

> returns true if left side is greater than right.

< returns true if left side is less than right side.


>= returns true if left side is greater than or equal to right side.

<= returns true if left side is less than or equal to right side.

Example of Relational operators


Note: This example is using if-else statement which is our next tutorial, if you
are finding it difficult to understand then refer if-else in Java.

public class RelationalOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if (num1==num2) {
System.out.println("num1 and num2 are equal");
}
else{
System.out.println("num1 and num2 are not equal");
}

if( num1 != num2 ){


System.out.println("num1 and num2 are not equal");
}
else{
System.out.println("num1 and num2 are equal");
}

if( num1 > num2 ){


System.out.println("num1 is greater than num2");
}
else{
System.out.println("num1 is not greater than num2");
}

if( num1 >= num2 ){


System.out.println("num1 is greater than or equal to num2");
}
else{
System.out.println("num1 is less than num2");
}

if( num1 < num2 ){


System.out.println("num1 is less than num2");
}
else{
System.out.println("num1 is not less than num2");
}

if( num1 <= num2){


System.out.println("num1 is less than or equal to num2");
}
else{
System.out.println("num1 is greater than num2");
}
}
}

Ternary Operator
This operator evaluates a boolean expression and assign the value based on
the result.
Syntax:

variable num1 = (expression) ? value if true : value if false


If the expression results true then the first value before the colon (:) is
assigned to the variable num1 else the second value is assigned to the num1.

Example of Ternary Operator


public class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
System.out.println( "num2: "+num2);

/* num1 is equal to 25 that's why


* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 25) ? 100: 200;
System.out.println( "num2: "+num2);
}
}
Java flow control Statements
There are three types of flow control statements in java
1) Selection Statements
2) Iteration statements
3) Transfer statements.

When we need to execute a set of statements based on a condition then we


need to use control flow statements. For example, if a number is greater
than zero then we want to print “Positive Number” but if it is less than zero
then we want to print “Negative Number”. In this case we have two print
statements in the program, but only one print statement executes at a time
based on the input value.

a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement.

If statement
If statement consists a condition, followed by statement or a set of statements
as shown below:

if(condition){
Statement(s);
}
The statements get executed only when the given condition is true. If the
condition is false then the statements inside if statement body are completely
ignored.

Nested if statement in Java


When there is an if statement inside another if statement then it is called
the nested if statement.
The structure of nested if looks like this:

if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only
execute if both the conditions (condition_1 and condition_2) are true.

Example of Nested if statement


public class NestedIfExample {

public static void main(String args[]){


int num=70;
if( num < 100 ){
System.out.println("number is less than 100");
if(num > 50){
System.out.println("number is greater than 50");
}
}
}
}

If else statement in Java


This is how an if-else statement looks:

if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the
statements inside “else” would execute if the condition is false.

if-else-if Statement
if-else-if statement is used when we need to check multiple conditions. In this
statement we have only one “if” and one “else”, however we can have multiple
“else if”. It is also known as if else if ladder. This is how it looks:

if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
Note: The most important point to note here is that in if-else-if statement, as
soon as the condition is met, the corresponding set of statements get
executed, rest gets ignored. If none of the condition is met then the
statements inside “else” gets executed.

Example of if-else-if
public class IfElseIfExample {

public static void main(String args[]){


int num=1234;
if(num <100 && num>=1) {
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100) {
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000) {
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000) {
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");

}
}
}

Switch Case statement in Java with example


Switch case statement is used when we have number of options (or choices)
and we may need to perform a different task for each choice.
The syntax of Switch case statement looks like this –

switch (variable or an integer expression)


{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}
Switch Case statement is mostly used with break statement even though it is
optional. We will first see an example without break statement and then we
will discuss switch case with break

A Simple Switch Case Example


public class SwitchCaseExample1 {

public static void main(String args[]){


int num=2;
switch(num+2)
{
case 1:
System.out.println("Case1: Value is: "+num);
case 2:
System.out.println("Case2: Value is: "+num);
case 3:
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}

Break statement in Switch Case


Break statement is optional in switch case but you would use it almost every
time you deal with switch case. Before we discuss about break statement,
Let’s have a look at the example below where I am not using the break
statement:

public class SwitchCaseExample2 {

public static void main(String args[]){


int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
case 2:
System.out.println("Case2 ");
case 3:
System.out.println("Case3 ");
case 4:
System.out.println("Case4 ");
default:
System.out.println("Default ");
}
}
}

Few points about Switch Case


1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any
integer value after case keyword. Also, case doesn’t need to be in an
ascending order always, you can specify them in any order based on the
requirement.

2) You can also use characters in switch case. for example –

public class SwitchCaseExample2 {

public static void main(String args[]){


char ch='b';
switch(ch)
{
case 'd':
System.out.println("Case1 ");
break;
case 'b':
System.out.println("Case2 ");
break;
case 'x':
System.out.println("Case3 ");
break;
case 'y':
System.out.println("Case4 ");
break;
default:
System.out.println("Default ");
}
}
}
For loop in Java with example
Loops are used to execute a set of statements repeatedly until a particular
condition is satisfied. In Java we have three types of basic loops: for, while
and do-while. In this tutorial we will learn how to use “for loop” in Java.

Syntax of for loop:


for(initialization; condition ; increment/decrement)
{
statement(s);
}

Flow of Execution of the for Loop


As a program executes, the interpreter always keeps track of which statement
is about to be executed. We call this the control flow, or the flow of execution
of the program.

First step: In for loop, initialization happens first and only one time, which
means that the initialization part of for loop only executes once.

Second step: Condition in for loop is evaluated on each iteration, if the


condition is true then the statements inside for loop body gets executed. Once
the condition returns false, the statements in for loop does not execute and
the control gets transferred to the next statement in the program after for loop.

Third step: After every execution of for loop’s body, the increment/decrement
part of for loop executes that updates the loop counter.

Fourth step: After third step, the control jumps to second step and condition
is re-evaluated.

Example of Simple For loop


class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}

For loop example to iterate an array:


Here we are iterating and displaying array elements using the for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}

Enhanced For loop


Enhanced for loop is useful when you want to iterate Array/Collections, it is
easy to write and understand.

Let’s take the same example that we have written above and rewrite it
using enhanced for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
}

While loop in Java with examples


Syntax of while loop
while(condition)
{
statement(s);
}

How while Loop works?


In while loop, condition is evaluated first and if it returns true then the
statements inside while loop execute. When condition returns false, the
control comes out of loop and jumps to the next statement after while loop.

Note: The important point to note when using while loop is that we need to use
increment or decrement statement inside while loop so that the loop variable
gets changed on each iteration, and at some point condition returns false. This
way we can end the execution of while loop otherwise the loop would execute
indefinitely.

Simple while loop example


class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}

do-while loop in Java with example


First, the statements inside loop execute and then the condition gets
evaluated, if the condition returns true then the control gets transferred to the
“do” else it jumps to the next statement after do-while.

do-while loop example


class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}

Continue statement is mostly used inside loops. Whenever it is encountered


inside a loop, control directly jumps to the beginning of the loop for next
iteration, skipping the execution of statements inside loop’s body for the
current iteration. This is particularly useful when you want to continue the loop
but do not want the rest of the statements(after continue statement) in loop
body to execute for that particular iteration.

Syntax:
continue word followed by semi colon.

continue;

Example: continue statement inside for loop


public class ContinueExample {
public static void main(String args[]){
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}

System.out.print(j+" ");
}
}
}

The break statement is usually used in following two scenarios:

a) Use break statement to come out of the loop instantly. Whenever a break
statement is encountered inside a loop, the control directly comes out of loop
and the loop gets terminated for rest of the iterations. It is used along with if
statement, whenever used inside loop so that the loop gets terminated for a
particular condition.

The important point to note here is that when a break statement is used inside
a nested loop, then only the inner loop gets terminated.

b) It is also used in switch case control. Generally all cases in switch case are
followed by a break statement so that whenever the program control jumps to
a case, it doesn’t execute subsequent cases (see the example below). As
soon as a break is encountered in switch-case block, the control comes out of
the switch-case body.

Syntax of break statement:


“break” word followed by semi colon

Example – Use of break in a while loop


In the example below, we have a while loop running from o to 100 but since
we have a break statement that only occurs when the loop value reaches 2,
the loop gets terminated and the control gets passed to the next statement in
program after the loop body.

public class BreakExample1 {


public static void main(String args[]){
int num =0;
while(num<=100)
{
System.out.println("Value of variable is: "+num);
if (num==2)
{
break;
}
num++;
}
System.out.println("Out of while-loop");
}
}

Example – Use of break in a for loop


The same thing you can see here. As soon as the var value hits 99, the for
loop gets terminated.

public class BreakExample2 {

public static void main(String args[]){


int var;
for (var =100; var>=10; var --)
{
System.out.println("var: "+var);
if (var==99)
{
break;
}
}
System.out.println("Out of for-loop");
}
}
Arrays
Introduction
 An array is an indexed collection of fixed number of homogeneous data
elements.
 The main advantage of arrays is we can represent multiple values with the
same name
So that readability of the code will be improved.
But the main disadvantage of arrays is:
 Fixed in size that is once we created an array there is no chance of
increasing or
Decreasing the size, based on our requirement that is to use arrays concept
compulsory
 We should know the size in advance which may not possible always.
We can resolve this problem by using collections.
Array declarations:
Example:
 int[] a; //recommended to use because name is clearly separated from the
 int []a;
 int a[];
Every array in java is an object hence we can create by using new operator.
Example:
 int[] a=new int[3];
Rule 1:
At the time of array creation compulsory we should specify the size otherwise we
will get compile time error.
Example:
 int[] a=new int[3];
 int[] a=new int[]; //C.E:array dimension missing
Rule 2:
It is legal to have an array with size zero in java.
Example:
 int[] a=new int[0];
 System.out.println(a.length);//0
Rule 3:
 If we are taking array size with -ve int value then we will get runtime
exception saying NegativeArraySizeException.
Example:
 int[] a=new int[-3];//R.E:NegativeArraySizeException
Rule 4:
 The maximum allowed array size in java is maximum value of int size
[2147483647].
Example:
 int[] a1=new int[2147483647];(valid)
 int[] a2=new int[2147483648];
 //C.E:integer number too large: 2147483648(invalid)
Note: Whenever we are trying to print any object reference internally toString()
method will be executed which is implemented by default to return the following.
classname@hexadecimalstringrepresentationofhashcode.
Note: If we are trying to access array element with out of range index we will get
Runtime Exception saying ArrayIndexOutOfBoundsException.
 Arrays are not used widely in Java but better to have an understanding of it,
as all the interview questions are from arrays wrt Algos and DS.
Few Practice problems on Arrays
 Find the Given number index
 Sum of elements in an array.
 Searching Algorithms
 Sorting Algorithms etc.

Var- arg methods (variable no of argument methods) (1.5)


 Until 1.4v we can't declared a method with variable no. Of arguments.
 If there is a change in no of arguments compulsory we have to define a new
method.
 This approach increases length of the code and reduces readability.
 But from 1.5 version onwards we can declare a method with variable no. Of
arguments such type of methods are called var-arg methods.
General method priority.
 In java we have 3 types of variables based on the area of declaration.

 Local variables.

 Instance Variables.

 Static Variables.

Local Variable

 Variables which are declared inside a method , constructor or block called local variable.

 Local variable will be created when the method or code block is executed by JVM and
destroyed after the method execution.

 No Access modifiers are allowed with a local variable.

 These variables are created in stack memory.

 There is no default value for local variables , we must initialize before the first usage of the
variable.

Instance Variables

 Variables which are declared inside a class but not inside any method , constructor or blocks.

 This variables are created when object is created to that class and destroyed when the object
is cleared from memory.

 We should declare Instance variables when we need to refer the same variable in multiple
methods or blocks.

 We can use all the Access modifiers with instance variables, generally we use private in IT
industry.

 Instance variables have default values provided by JVM, for numbers the default value is zero ,
for Boolean variables it is false, for objects it is null.

 These variables value can be set in multiple ways.

1)At the time of declaration we can set.

2)Through Constructor.

3)Through getter and setter methods.

4)Through Object reference.


Static Variables

 Static variables are also called as Class Variables.

 These variables are also declared inside a class but not inside any method or block.

 Static key word is used along with the variable declaration.

 The major difference with static and non static variables is the Memory allocation.

 Access modifiers usage is similar to instance variables.

 Default values are also same as instance variables,

 For numbers zero ,Boolean – false, objects – null.

 Static variables are accessed with the class name.

 Syntax: ClassName.variableName

 In our day to day programming , we use static when the variable should be constant in entire
application.

 example : public static final int favouriteNumber=2;

msclns

 Variable which hold primitive values are called primitive variables remaining are called
reference variables.

 We know 8 primitive data types in java , but what are these reference variables?

ex: int id=200; (id is primitive variable);

Employee e;(Here e is reference variable)

• We can not use instance variable in static area.

Static Methods vs Non Static

 Like variables we have two types of methods also

1)Static Method

2)Non Static method.


Class & Object
• A class is a user defined blueprint or prototype from
which objects are created.
• A class is a collection of fields , methods and
constructor.
Object …
 It is a basic unit of Object Oriented Programming and
represents the real life entities.
 When an object of a class is created, the class is said to
be instantiated.
Constructor
 Object creation syntax:-
Test t = new Test();
 Test  class Name
t  Reference variables
 =  assignment operator
 new  keyword used to create object
 Test () -- constructor
 ; -- statement terminator
 When we create new instance (Object) of a class using new
keyword, a constructor for that class is called.
 Constructors are used to initialize the instance variables of
a class.
Rules to declare Constructor
1) Constructor name class name must be same.
2) Constructor is able to take parameters.
3) Constructor not allowed explicit return type
(return type declaration not possible).
Types of Constructor
 1) Default Constructor (provided by compiler).
 2) User defined Constructor (provided by user) or
parameterized constructor.
Default Constructor
1) If we don’t write constructor for a class then compiler
generates one constructor for you that constructor is
called default constructor, And it is not visible in code.
2) Compiler generates Default constructor inside the
class when we are not providing any type of
constructor (0-arg or parameterized).
3) The compiler generated default constructor is always
0-argumnetconstructor with empty
implementation (empty body).
User Defined Constructor
 Inside the class if we are declaring at least one
constructor that is called user defined constructor.
 The main objective of constructor is initialize some
values to instance variables during object creation
time.
 Constructors are used to write the functionality of
project that functionality is executed during object
creation.
 Inside the class it is possible to declare multiple
constructors.
Two Formats of Object creation.
 Eager Object creation
 Lazy Object creation.
Example:
//Eager object creation approach
Test t = new Test();
t.m1();
//lazy object creation approach
Test t1;
t1=new Test();
t1.m1();
Constructor Chaining
 Calling a constructor inside a constructor is possible
 Constructor call should be the first statement
 this can be used to access the current class variables ,
methods and the constructors.
 Constructor creation restriction
 Singleton design pattern and its usages in real time
with example.
 Mandatory variables creation via constructor
OOPS
Oops concepts:-

1. Inheritance

2. Polymorphism

3. Abstraction

4. Encapsulation.

Inheritance.
 The process of acquiring fields(variables) and methods(behaviors) from one
class to another class is called inheritance.
 The main objective of inheritance is code extensibility whenever we are
extending class automatically the code is reused.
 In inheritance one class giving the properties and behavior & another class
is taking the properties and behavior.
 Inheritance is also known as is-a relationship. By using extends keyword we
are achieving inheritance concept.
 extends keyword used to achieve inheritance & it is providing relationship
between two classes .
 In java parent class is giving properties to child class and Child is acquiring
properties from Parent.
 To reduce length of the code and redundancy of the code sun people
introduced inheritance concept.

Application Code before Inheritance vs After inheritance

 With Child Object we can call parent props/methods( summary)


Simple examples
Types Of Inheritance
There are five types of inheritance in java
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid Inheritance
Single inheritance:-
 One class has one and only one direct super class is called single
inheritance.
 In the absence of any other explicit super class, every class is implicitly a
subclass of Object class.

Multilevel inheritance:-
 One Sub class is extending Parent class then that sub class will
become Parent class of next extended class this flow is called
multilevel inheritance.
Code Snippet

Hierarchical inheritance :-
 More than one sub class is extending single Parent is called
hierarchical inheritance.

Example Code

 Class Children and GrandChildren both extending Parent class


Multiple inheritance:-
 One sub classis extending more than one super class is called Multiple
inheritance and java not supporting multiple inheritance because it is
creating ambiguity problems (confusion state) .
 As Java not supporting multiple inheritance hence in java one class able to
extends only one class at a time but it is not possible to extends more than
one class.

Example Code

Hybrid inheritance:-
Hybrid is combination of any two or more inheritances.
Preventing inheritance:-
 You can prevent sub class creation by using final keyword in the parent
class declaration.

Need to discuss on HAS-A relation .


Super keyword:-
Super keyword is holding super class object. And it is representing
 Super class variables
 Super class methods
 Super class constructors.
 Current class variables/methods/constructors are called with this variable
where as parent class or super class variables/methods/constructors are
called with super keyword.
 If both variables having same name in both the class then we will use this,
super to segregate it.
Polymorphism:-
Polymorphism is the ability of an object to take on many forms
 Polymorphism shows same functionality(method name same) with
different logics execution.
 The ability to appear in more forms is called polymorphism.
 Polymorphism is a Greek word poly means many and morphism means
forms.
There are two types of polymorphism in java
 Compile time polymorphism / static binding / early binding
[method execution decided at compilation time]
Example :- method overloading.
 Runtime polymorphism /dynamic binding /late binding.
 [Method execution decided at runtime].
Example :- method overriding.

 If we want achieve overloading concept one class is enough.


 It is possible to overload any number of methods in single java class.

Compile time polymorphism [Method Overloading]:-


 If java class allows two or more methods with same name but different
number of arguments such type of methods are called overloaded
methods.
 2) We can overload the methods in two ways in java language
a. By passing different number of arguments to the same methods.
void m1(int a){}
void m1(int a,int b){}
b. Provide the same number of arguments with different data types.
void m1(int a){}
void m1(char ch){}
 If we want achieve overloading concept one class is enough.
 It is possible to overload any number of methods in single java class.

Types of overloading:-
 Method overloading explicitly by the programmer
 Constructor overloading.
Runtime polymorphism [Method Overriding]:-
 If we want to achieve method overriding we need two class with parent
and child relationship.
 The parent class method contains some implementation (logics).
a. If child is satisfied use parent class method.
b. If the child class not satisfied (required own implementation) then
override the method in Child class.
 A subclass has the same method as declared in the super class it is known
as method overriding.
 The parent class method is called ===> overridden method
 The child class method is called ===> overriding method

While overriding methods must fallow these rules:-


 While overriding child class method signature & parent class method
signatures must be same otherwise we are getting compilation error.
 The return types of overridden method & overriding method must be same.
 While overriding the methods it is possible to maintains same level
permission or increasing order but not decreasing order, if you are trying to
reduce the permission compiler generates error message “attempting to
assign weaker access privileges ”.
 You are unable to override final methods. (Final methods are preventing
overriding)
 Static methods are bounded with class hence we are unable to override
static methods.
 If a subclass defines a static method with the same signature as a static
method in the superclass, then the method in the subclass hides the one in
the superclass.

Parent class reference variable is able to hold child class


object but Child class reference
variable is unable to hold parent class object.

Abstraction:-
There are two types of methods in java based on signature.
a. Normal methods
b. Abstract methods

Normal methods:- (component method/concrete method)


 Normal method is a method which contains method declaration as well as
method implementation.
Example:-
void m1() --->method declaration
{
body; --->method implementation
}
Abstract methods:-
 The method which is having only method declaration but not method
implementations such type of methods are called abstract Methods.
 In java every abstract method must end with “;”.
Example : - abstract void m1 (); ----> method declaration

Based on above representation of methods the classes are divided into two types
1) Normal classes.
2) Abstract classes.
Normal classes:-
 Normal class is a ordinary java class it contains only normal methods .
Example:-
class Test //normal class
{ void m1(){body;} //normal method
Abstract class:-
If any abstract method inside the class that class must be abstract.
. Abstract modifier:-
 Abstract modifier is applicable for methods and classes but not for
variables.
 To represent particular class is abstract class and particular method is
abstract method to the compiler use abstract modifier.
 The abstract class contains declaration of abstract methods , it says abstract
class partially implemented class hence for partially implemented classes
object creation is not possible.
 If we are trying to create object of abstract class compiler generate error
message “class is abstract con not be instantiated”.
 Abstract class may contains abstract methods or may not contains
abstract methods but object creation is not possible.

Interfaces
 Interface is also one of the type of class it contains only abstract methods.
And Interfaces not alternative for abstract class it is extension for abstract
classes.
 The abstract class contains at least one abstract method but the interface
contains only abstract methods.
 Interfaces giving the information about the functionalities and these are
not giving the information about internal implementation.
 Inside the source file it is possible to declare any number of interfaces. And
we are declaring the interfaces by using interface keyword.
 Interface contains abstract method, for these abstract methods provide the
implementation in the implementation classes.
 Implementation class is nothing but the class that implements particular
interface.
 While providing implementation of interface methods that implementation
methods must be public methods otherwise compiler generate error
message “attempting to assign weaker access privileges”.
Marker interface :-
 An interface that has no members (methods and variables) is known
as marker interface or tagged interface or ability interface.
 In java whenever our class is implementing marker interface our class
is getting some capabilities .
Ex:- serializable , Cloneable , RandomAccess…etc
 By default the methods which are in interface are public abstract.
 The interface contains constants and these constants by default
public static final.
 For the interfaces object creation is not possible.
 Difference between abstract classes & interfaces?
Abstract Class interfaces
The purpose of abstract class is to It is providing complete
specify default functionality of an abstraction
object and let its sub classes layer and it contains only
explicitly implement that declarations of the project then
functionality. write the implementations in
implementation classes.
An abstract class is a class that Declare the interface by using
declared with abstract modifier interface keyword.
The abstract allows declaring The interface allows declaring
both abstract & concrete only abstract methods.
methods.
The abstract class is able to The interface contains abstract
provide implementations of methods write the
interface methods implementations
in implementation classes.
One java class is able to extends One java class is able to
only one abstract class at a time. implements multiple interfaces at
a time
Inside abstract class it is possible Inside interface it is not possible
to declare constructors to declare methods and
constructors.
It is not possible to instantiate It is not possible to instantiate
abstract class. Interfaces also.

Encapsulation:-
The process of binding the data and code as a single unit is called encapsulation.
We are able to provide more encapsulation by taking the private data(variables)
members.
To get and set the values from private members use getters and setters to set the
data and to get the data.
Public modifier:-
Public modifier is applicable for variables,methods,classes.
All packages are able to access public members.
Default modifier:-
It is applicable for variables,methods,classes.
We are able to access default members only within the package and it is not
possible to access
outside package .
Default access is also known as package level access.
The default modifier in java is default.
Private modifier:-
private modifier applicable for methods and variables.
We are able to access private members only within the class and it is not
possible to access even
in child classes.
Protected modifier:-
Protected modifier is applicable for variables,methods.
We are able access protected members with in the package and it is possible to
access outside
packages also but only in child classes.
But in outside package we can access protected members only by using child
reference. If wetry
to use parent reference we will get compile time error.
Aggregation in Java
If a class have an another class as reference, it is known as Aggregation.
Aggregation represents HAS-A relationship.

class Employee{

int id;

String name;

Address address;//Address is a class

...

public class Address {

String city,state,country;

public Address(String city, String state, String country) {

this.city = city;

this.state = state;

this.country = country;

—--

Composition
Composition is a "belong-to" type of relationship in which one object is logically
related with other objects. It is also referred to as "has-a" relationship.

A classroom belongs to a school, or we can say a school has a classroom.


Composition is a strong type of "has-a" relationship because the containing object is
its owner. So, objects are tightly coupled, which means if we delete the parent object,
the child object will also get deleted with it.

class Car {

private Engine engine;

public Car() {

this.engine = new Engine();

// Other methods and attributes of the Car class

class Engine {

// Engine implementation

Aggregation
Aggregation relationship is also a "has-a" relationship. The only difference between
Aggregation and Composition is that in Aggregation, objects are not tightly coupled
or don't involve owning. All the objects are independent of each other and can exist
even if the parent object gets deleted.
Real-time example: Consider a University class that has an aggregation relationship
with Student class. The University class has a collection of Student objects, but the
Student objects can exist even if the University is destroyed.

Code :

class University {

private List<Student> students;

public University() {

this.students = new ArrayList<>();

public void addStudent(Student student) {

students.add(student);

// Other methods and attributes of the University class

class Student {

// Student implementation

In this example, the University class aggregates Student objects. The University has
a collection of Student objects, but the lifecycle of the Student objects is not tied to
the University object. If the University is destroyed, the Student objects can still exist.

In summary, composition represents a strong relationship where the composed


objects cannot exist independently, while aggregation represents a weaker
relationship where the aggregated objects can exist independently of the container
object.
Exception Handling
Information regarding Exception
 Dictionary meaning of the exception is abnormal termination.
 An un expected event that disturbs or terminates normal flow of execution
called exception.
 If the application contains exception then the program terminated
abnormally the rest of the application is not executed.
 To overcome above limitation in order to execute the rest of the
application must handle the exception.
In java we are having two approaches to handle the exceptions.
1) By using try-catch block.
2) By using throws keyword.

Exception Handling:-
 The main objective of exception handling is to get normal termination of
the application in order to execute rest of the application code.
 Exception handling means just we are providing alternate code to continue
the execution of remaining code and to get normal termination of the
application.
 Every Exception is a predefined class present in different packages.
 java.lang.ArithmeticException
 java.io.IOException
 java.sql.SQLException
 javax.servlet.ServletException
The exception are occurred due to two reasons
a. Developer mistakes
b. End-user mistakes.
i. While providing inputs to the application.
ii. Whenever user is entered invalid data then Exception is occur.
iii. A file that needs to be opened can’t found then Exception is occurred.
iv. Exception is occurred when the network has disconnected at the middle of the
communication.
Types of Exceptions:-
As per the sun micro systems standards The Exceptions are divided into three
types
1) Checked Exception
2) Unchecked Exception
3) Error
checked Exception:-
 The Exceptions which are checked by the compiler at the time of
compilation is called Checked Exceptions.
IOException,SQLException,InterruptedException……..etc
 If the application contains checked exception the code is not compiled so
must handle the checked Exception in two ways
 By using try-catch block.
 By using throws keyword.
If the application contains checked Exception the compiler is able to check it and
it will give intimation to developer regarding Exception in the form of compilation
error.

Exception handling key words:-


1) try
2) catch
3) finally
4) throw
5) throws
Exception handling by using Try –catch block:-
Syntax:-
try
{
exceptional code;
}
catch (ExceptionName reference_variable)
{
Code to run if an exception is raised;
}

Example : code.

1) Whenever the exception is raised in the try block JVM won’t terminate the
program immediately , it will search corresponding catch block.
a. If the catch block is matched that will be executed then rest of the application
executed and program is terminated normally.
b. If the catch block is not matched program is terminated abnormally.

Example code : //

 If there is no exception in try block the catch blocks are not checked
 in Exception handling independent try blocks are not allowed must
declare try-catch or try-finally or try-catch-finally.
 In between try-catch blocks it is not possible to declare any
statements must declare try with immediate catch block.
 If the exception raised in try block remaining code of try block won’t be
executed.
 Once the control is out of the try block the control never entered into try
block once again.
 The way of handling the exception is varied from exception to the
exception hence it is recommended to provide try with multiple
number of catch blocks.
 By using Exception catch block we are able to hold any type of
exceptions.
 if we are declaring multiple catch blocks at that situation the catch
block order should be child to parent shouldn’t be parent to the child.
 It is possible to combine two exceptions in single catch block the syntax is
catch(ArithmeticException | StringIndexOutOfBoundsException a).

Finally block:-
1) Finally block is always executed irrespective of try and catch.
2) It is used to provide clean-up code
a. Database connection closing. Connection.close();
b. streams closing. Scanner.close();
c. Object destruction . Test t = new Test();t=null;

It is not possible to write finally alone.


a. try-catch-finally -- valid
b. try-catch -- valid
c. catch-finally -- invalid
d. try-catch-catch-finally -- valid
e. try-finally -- valid
f. catch-catch-finally -- invalid
g. Try -- invalid
h. Catch -- invalid
i. Finally - invalid.

Syntax:-
try
{ risky code;
}
catch (Exception obj)
{ handling code;
}
finally
{ Clean-up code;(database connection closing, streams closing……etc)
}

Example:-in only two cases finally block won’t be executed


Case 1:- whenever we are giving chance to try block then only finally block will be
executed otherwise it is not executed.
Case 2:-In your program whenever we are using System.exit(0) the JVM will be
shutdown hence the rest of the code won’t be executed.

throws
The main purpose of the throws keyword is bypassing the generated exception
from present method to caller method.
 Use throws keyword at method declaration level.
It is possible to throws any number of exceptions at a time based on the
programmer requirement.
If main method is throws the exception then JVm is responsible to handle the
exception.

Example code : //

Throw:-
1) The main purpose of the throw keyword is to creation of Exception object
explicitly either for predefined or user defined exception.
2) Throw keyword works like a try block. The difference is try block is
automatically find the situation and creates an Exception object implicitly.
Whereas throw keyword creates an Exception object explicitly.
3) Throws keyword is used to delegate the responsibilities to the caller method
but throw is used to create the exception object.
4) If exception object created by JVM it will print predefined information (/ by
zero) but if
exception Object created by user then user defined information is printed.
5) We are using throws keyword at method declaration level but throw keyword
used at method implementation (body) level.

Different types of Exceptions in java:-


Checked Exception ---> Description
ClassNotFoundException --> If the loaded class is not available
CloneNotSupportedException-->
Attempt to clone an object that does not implement the Cloneable
interface.
 IllegalAccessException --> Access to a class is denied.
 InstantiationException --> Attempt to create an object of an abstract class
or interface.
 InterruptedException --> One thread has been interrupted by another
thread.
 NoSuchFieldException --> A requested field does not exist.
 NoSuchMethodException --> If the requested method is not available.
UncheckedException Description
 ArithmeticException Arithmetic error, such as divide-by-zero.
 ArrayIndexOutOfBoundsException Array index is out-of-bounds.(out of
range)
 InputMismatchException If we are giving input is not matched for storing
input.
 ClassCastException If the conversion is Invalid.
 IllegalArgumentException Illegal argument used to invoke a method.
 IllegalThreadStateException Requested operation not compatible with
current thread state.
 IndexOutOfBoundsException Some type of index is out-of-bounds.
 NegativeArraySizeException Array created with a negative size.
 NullPointerException Invalid use of a null reference.
 NumberFormatException Invalid conversion of a string to a numeric
format.
 StringIndexOutOfBoundsException Attempt to index outside the bounds of
a string.
Multi Threading
Thread:-
1) Thread is nothing but a separate path of sequential execution.
2) The independent execution technical name is called thread.
3) Whenever different parts of the program are executed simultaneously,
each and every part is called thread.
4) The thread is a light weight process because whenever we are creating
a thread it is not occupying the separate memory it uses the same memory.
Whenever the memory is shared means it is not consuming more memory.
5) Executing more than one thread a time is called multithreading.
Information about main Thread
When a Java program starts one Thread is running immediately. That
thread is called the main thread of your program.
1. It is used to create a new Thread(child Thread).
2. It must be the last thread to finish the execution because it performs
various actions.
It is possible to get the current thread reference by using currentThread()
method; it is a static public method present in Thread class.
The main important application areas of the multithreading are
1. Developing video games
2. Implementing multimedia graphics.
3. Developing animations

=========================================
A thread can be created in two ways:-
1) By extending Thread class.
2) By implementing java.lang.Runnable interface.

1)Extending thread class


class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();//Instantiation of a Thread
t.start();//starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}.

Thread Scheduler:
· If multiple Threads are waiting to execute then which Thread will execute
1st is decided by “Thread Scheduler” which is part of JVM.
· Which algorithm or behavior followed by Thread Scheduler we can’t
expect exactly is the JVM vendor dependent hence in multithreading.

Difference between t.start() and t.run() methods.


· In the case of t.start() a new Thread will be created which is responsible
for the execution of run() method. But in the case of t.run() no new Thread
will be created and run() method will be executed just like a normal method
by the main Thread.

importance of Thread class start() method.


· For every Thread the required mandatory activities like registering the
Thread with Thread Scheduler will be taken care by Thread class start()
method and the programmer is responsible just to define the job of the
Thread inside run() method.

If we are not overriding run() method:


· If we are not overriding the run() method then the Thread class run()
method will be executed which has empty implementation and hence we
won’t get any output.

Overloading of run() method.


· We can overload run() method but Thread class start() method always
invokes no argument run() method the other overload run() methods we
have to call explicitly then only it will be executed just like normal method.

Thread Life Cycle


Life cycle stages are:-
1) New
2) Ready
3) Running state
4) Blocked / waiting / non-running mode
5) Dead state

1)New :- MyThread t=new MyThread();

2)Ready :- t.start()

3)Running state:- If thread scheduler allocates CPU for particular thread.


Thread goes to running state
The Thread is running state means the run() is executed.
4)Blocked State:-
If the running thread gets interrupted or goes to a sleeping state at that
moment it goes to the blocked state.

5)Dead State:-If the business logic of the project is completed means run()
over thread goes dead state.

❖ After starting a Thread we are not allowed to restart the same Thread
once again otherwise we will get a runtime exception saying
“IllegalThreadStateException”.

Second way of creating a Thread.

● We can define a Thread even by implementing Runnable interface


also. Runnable interface present in java.lang.pkg and contains only
one method run().
Example code :
class ThreadDemo
{
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);//here r is a Target Runnable
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}

So which is the best way of creating the thread ?


➔ Among the 2 ways of defining a Thread, implementing a Runnable
approach is always recommended.
➔ · In the 1st approach our class should always extend Thread class
there is no chance of extending any other class hence we are missing
the benefits of inheritance.
➔ · But in the 2nd approach while implementing Runnable interface
we can extend some other classes also.
➔ Hence implementing a Runnable mechanism is recommended to
define a Thread.

Naming Thread
The Thread class provides methods to change and get the name of a
thread. By default, each thread has a name i.e. thread-0, thread-1 and so
on …
We can change the name of the thread by using setName() method. The
syntax of setName() and getName() methods are given below
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a
thread.

❖ We can get current executing Thread object reference by using


Thread.currentThread() method.

Priority of a Thread (Thread Priority)


★ Each thread has a priority.
★ Priorities are represented by a number between 1 and 10.
★ In most cases, thread schedules the threads according to their
priority (known as preemptive scheduling).
★ But it is not guaranteed depending on JVM specification which
scheduling it chooses.
3 constants defined in Thread class:
❖ 1. public static int MIN_PRIORITY
❖ 2. public static int NORM_PRIORITY
❖ 3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

The Methods to Prevent a Thread from Execution:


· We can prevent(stop) a Thread execution by using the following methods.
1) yield();
2) join();
3) sleep();

yield()
❖ Suppose there are three threads t1, t2, and t3. Thread t1 gets the
processor and starts its execution .
❖ Thread t2 and t3 are in Ready/Runnable state.
❖ Completion time for thread t1 is 5 hour and completion time for t2 is 5
minutes. Since t1 will complete its execution after 5 hours, t2 has to wait
for 5 hours to just finish the 5 minutes job.
❖ In such scenarios where one thread is taking too much time to complete its
execution, we need a way to prevent execution of a thread in between if
something important is pending.
❖ yeild() helps us in doing so.
❖ yield() basically means that the thread is not doing anything particularly
important and if any other threads or processes need to be run, they
should run. Otherwise, the current thread will continue to run.
Use of yield method:
● Whenever a thread calls java.lang.Thread.yield method, it gives a hint
to the thread scheduler that it is ready to pause its execution. Thread
scheduler is free to ignore this hint.
● If any thread executes the yield method , the thread scheduler checks if
there is any thread with same or higher priority than this thread. If the
processor finds any thread with higher or same priority then it will move
the current thread to Ready/Runnable state and give the processor to
another thread and if not – current thread will keep executing.

Example code
Note:
● Once a thread has executed the yield method and there are many
threads with the same priority waiting for the processor, then we can't
specify which thread will get an execution chance first.
● The thread which executes the yield method will enter in the Runnable
state from Running state.
● Once a thread pauses its execution, we can't specify when it will get a
chance again; it depends on the thread scheduler.
● Underlying platform must provide support for preemptive scheduling if
we are using yield methods

sleep(): This method causes the currently executing thread to sleep for the
specified number of milliseconds, subject to the precision and accuracy of
system timers and schedulers..
// sleep for the specified number of milliseconds
public static void sleep(long millis) throws
InterruptedException

//sleep for the specified number of milliseconds plus nano


seconds
public static void sleep(long millis, int nanos)
throws InterruptedException

Note:
● Based on the requirement we can make a thread to be in sleeping state
for a specified period of time
● Sleep() causes the thread to definitely stop executing for a given
amount of time; if no other thread or process needs to be run, the CPU
will be idle (and probably enter a power saving mode).
Join() : The join() method of a Thread instance is used to join the start of a
thread’s execution to the end of another thread’s execution such that a
thread does not start running until another thread ends. If join() is called on a
Thread instance, the currently running thread will block until the Thread instance
has finished executing.
==========================
Synchronization
● Synchronized is the keyword applicable for methods and blocks but not for
classes and variables.
● · If a method or block is declared as synchronized then at a time only one Thread
is allowed to execute that method or block on the given object.
● · The main advantage of synchronized keywords is we can resolve data
inconsistency problems.
● · But the main disadvantage of synchronized keyword is it increases waiting time
of the Thread and affects performance of the system.
● · Hence if there is no specific requirement then never recommend to use
synchronized keywords.
● · Internally synchronization concept is implemented by using lock concept.
● · Every object in java has a unique lock. Whenever we are using synchronized
keywords then only the lock concept will come into the picture.
● ·If a Thread wants to execute any synchronized method on the given object , 1st
it has to get the lock of that object.
● Once a Thread gets the lock of that object then it’s allowed to execute any
synchronized method on that object. If the synchronized method execution
completes then automatically Thread releases lock.
● While a Thread executing any synchronized method the remaining Threads are
not allowed to execute any synchronized method on that object simultaneously.
But remaining Threads are allowed to execute any non-synchronized method
simultaneously. [lock concept is implemented based on object but not based on
method]

Example code :

package sync;

public class SourceSyncTest {

public static void main(String[] args) {

SourceTable s = new SourceTable();

M1 m1 = new M1();
m1.s1 = s;
M2 m2 = new M2();
m2.s1 = s;

m1.start();

m2.start();
}

class M1 extends Thread {

SourceTable s1;

@Override
public void run() {

s1.tablePrint(5);

class M2 extends Thread {

SourceTable s1;

@Override
public void run() {
s1.tablePrint(10);

Source table:
package sync;

public class SourceTable {

public static void tablePrint(int tableNo) {


for (int i = 0; i < 10; i++) {

System.out.println(tableNo+" * "+i+" = "+(tableNo*i));


}
}

For Synchronization.

If multiple threads operate on the same java object ,then only


synchronization is required ,if each thread is working on a different
instance of class then there is no need of synchronization.

SourceTable source1= new SourceTable();


SourceTable source1 = new SourceTable();

M1 m1 = new M1();
m1.s1 = source1;
M2 m2 = new M2();
m2.s1 = source1;

m1.start();

m2.start();
Now both the threads are working on different objects.

Even we make it sync no use as they are operating on individual objects.

Make them as static methods and get class level locks.


T1 ,T2 , T3 , T4 ⇒ 4threads.

T1 acquires class level lock while executing m1 method.

T2 which is intended to execute the m1() method will be in wait state.

T3 which is intended to execute the m2() method will be in wait state.

T4 can execute m3().

I.e : remaining threads can execute normal static methods, normal instance
methods.

Class level lock in Java


Every class in java has a unique lock called class level lock ,similarly every object in java has
object level lock.
When thread is going to execute a static synchronized method/block it requires class level lock.

Class level lock prevents multiple threads to enter in synchronized block in


any of all available instances of the class on runtime. This means if in
runtime there are 100 instances of DemoClass, then only one thread will be
able to execute demoMethod() in any one of instance at a time, and all
other instances will be locked for other threads.
Class level locking should always be done to make static data thread safe.
As we know that static keywords associate data of methods to class level,
so use locking at static fields or methods to make it on class level.

Object level lock in Java


Object level lock is a mechanism when we want to synchronize a non-static
method or non-static code block such that only one thread will be able to
execute the code block on a given instance of the class. This should always be
done to make instance level data thread safe.
Synchronized block:
· If very few lines of the code required synchronization then it’s never
recommended to declare the entire method as synchronized we have to enclose
those few lines of the code within the synchronized block.
· The main advantage of synchronized block over synchronized method is it
reduces waiting time of Thread and improves performance of the system.

Inter Thread communication (wait(),notify(), notifyAll()):


❖ Two Threads can communicate with each other by using wait(),
notify() and notifyAll() methods.
❖ · The Thread which is expecting updation it has to call wait()
method and the Thread which is performing updation it has to
call notify() method.
❖ After getting notification the waiting Thread will get those updations.
❖ wait(), notify() and notifyAll() methods are available in Object class but not
in Thread class because Thread can call these methods on any common
object.
❖ start(), join() we can call on only thread objects but wait , notify should be
called on any java object by the waiting or notifying threads .
❖ To call wait(), notify() and notifyAll() methods compulsory the current
Thread should be the owner of that object that is current Thread should
have lock of that object that is current Thread should be in
synchronized area.
❖ Hence we can call wait(), notify() and notifyAll() methods only from
synchronized area otherwise we will get runtime exception saying
IllegalMonitorStateException.

Notify vs NotifyAll.

notify() and notifyAll() methods with wait() method are used for communication
between the threads. A thread which goes into a waiting state by calling wait()
method will be in waiting state until any other thread calls either notify() or
notifyAll() method on the same object.

Notifying a thread by JVM : If multiple threads are waiting for the notification
and we use notify() method then only one thread gets the notification and
the remaining thread has to wait for further notification. Which thread will get the
notification we can’t expect because it totally depends upon the JVM. But when
we use notifyAll() method then multiple threads get the notification but execution
of threads will be performed one by one because thread requires lock and only
one lock is available for one object.
Object class in Java
The Object class is the parent class of all the classes in java by default. In other words,
it is the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as
upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of
any type like Employee,Student etc, we can use Object class reference to refer that
object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this
method

The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description

public final Class returns the Class class object of this object. The Class

getClass() class can further be used to get the metadata of this

class.

public int hashCode() returns the hashcode number for this object.

public boolean compares the given object to this object.

equals(Object obj)
protected Object clone() creates and returns the exact copy (clone) of this object.

throws

CloneNotSupportedExcept

ion

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's

monitor.

public final void wait(long causes the current thread to wait for the specified

timeout)throws milliseconds, until another thread notifies (invokes

InterruptedException notify() or notifyAll() method).

public final void wait(long causes the current thread to wait for the specified

timeout,int nanos)throws milliseconds and nanoseconds, until another thread

InterruptedException notifies (invokes notify() or notifyAll() method).

public final void causes the current thread to wait, until another thread

wait()throws notifies (invokes notify() or notifyAll() method).

InterruptedException

protected void is invoked by the garbage collector before the object is

finalize()throws Throwable being garbage collected.


Strings
Java.lang.String:-

String is used to represent group of characters or character array enclosed with in


the double quotes.

Various ways of creating String in Java

There are two ways to create String object:

1. By string literal

2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is created
and placed in the pool. For example:
1. String s1="Welcome";

2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find
any string object with the value "Welcome" in string constant pool, that is why it
will create a new object. After that it will find the string with the value "Welcome"
in the pool, it will not create a new object but will return the reference to the
same instance.

Note: String objects are stored in a special memory area known as the "string
constant pool".

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).
2) By new keyword

1. String s=new String("Welcome");

In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool. The
variable s will refer to the object in a heap (non-pool).
Example program to show both are of same locations
Concat Operation
Difference between (==) and equals method in java ?

Utility Methods in String class ...

a)indexOf

b)charAt

c)substring() {overloaded methods}

d)replace()
e)toUpperCase()

f)toLowerCase()

g)split();

h)replace();

i)equals

j)equalsIgnoreCase()

String Buffer class In Java ? (Mutable)


String Builder vs String Buffer ?
Type Casting

In Java, type casting refers to the process of converting a data type into another data
type, and it can be accomplished both manually and automatically. The compiler
handles automatic conversions, while manual conversions are performed by the
programmer.

Type casting involves converting a value from one data type to another, and there are
two primary types of type casting:

​ Widening Type Casting:


● This type of casting involves converting a lower data type into a higher
one.
● Also known as implicit conversion or casting down.
● It occurs automatically and is considered safe because there is no risk
of data loss.
● Conditions for widening type casting:
● Both data types must be compatible.
● The target type must be larger than the source type.
● Order of widening type casting: byte -> short -> char -> int ->
long -> float -> double
​ Narrowing Type Casting:
● This type of casting involves converting a higher data type into a lower
one.
● Also known as explicit conversion or casting up.
● It is performed manually by the programmer.
● If casting is not explicitly done, the compiler will generate a
compile-time error.
● Order of narrowing type casting: double -> float -> long -> int
-> char -> short -> byte
Wrapper classes 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.

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.

○ 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.

○ Synchronization: Java synchronization works with objects in Multithreading.

○ java.util package: The java.util package provides the utility classes to deal
with objects.

○ 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.

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,
long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
//Java program to convert primitive into objects

//Autoboxing example of int to Integer

public class WrapperExample1{

public static void main(String args[]){

//Converting int into Integer

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

System.out.println(a+" "+i+" "+j);

}}

Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not
need to use the intValue() method of wrapper classes to convert the wrapper type
into primitives.

Wrapper class Example: Wrapper to Primitive

//Java program to convert object into primitives

//Unboxing example of Integer to int

public class WrapperExample2{

public static void main(String args[]){

//Converting Integer to int

Integer a=new Integer(3);


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

int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);

}}
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.

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

A Collection represents a single unit of objects, i.e., a group.

No. Method Description


1 public boolean add(E e) It is used to insert an element in this

collection.

2 public boolean It is used to insert the specified collection

addAll(Collection<? extends elements in the invoking collection.

E> c)

3 public boolean It is used to delete an element from the

remove(Object element) collection.

4 public boolean It is used to delete all the elements of the

removeAll(Collection<?> c) specified collection from the invoking

collection.

5 default boolean It is used to delete all the elements of the

removeIf(Predicate<? super collection that satisfy the specified predicate.

E> filter)

6 public boolean It is used to delete all the elements of invoking

retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in the

collection.

8 public void clear() It removes the total number of elements from

the collection.

9 public boolean It is used to search an element.

contains(Object element)
10 public boolean It is used to search the specified collection in

containsAll(Collection<?> c) the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the

runtime type of the returned array is that of the

specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the

parallelStream() collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the

collection as its source.

17 default Spliterator<E> It generates a Spliterator over the specified

spliterator() elements in the collection.

18 public boolean equals(Object It matches two collections.

element)

19 int hashCode() It returns the hash code number of the

collection.

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:

N Method Description
o.

1 public boolean It returns true if the iterator has more elements otherwise

hasNext() it returns false.

2 public Object next() It returns the element and moves the cursor pointer to the

next element.

3 public void It removes the last elements returned by the iterator. It is

remove() less used.

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
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();
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.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.

package com.flm;
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();// Creating arraylist
list.add("Ravi");// Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

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 java.util package. It is like the Vector in C++.

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.

It inherits the AbstractList class and implements List interface.

The important points about the Java ArrayList class are:

○ Java ArrayList class can contain duplicate elements.


○ Java ArrayList class maintains insertion order.

○ Java ArrayList class is non synchronized.

○ In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.

○ We can not 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. For example:

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


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

○ Java ArrayList gets initialized by the size. The size is dynamic in the array list, which
varies according to the elements getting added or removed from the list

Constructors of ArrayList

onstructor Description

ayList() It is used to build an empty array list.

ayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the

collection c.

ayList(int capacity) It is used to build an array list that has the specified initial capacity.
Methods of ArrayList

Method Description

void add(int index, E It is used to insert the specified element at the specified

element) position in a list.

boolean add(E e) It is used to append the specified element at the end of a list.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean addAll(int It is used to append all the elements in the specified

index, Collection<? collection, starting at the specified position of the list.

extends E> c)

void clear() It is used to remove all of the elements from this list.
void It is used to enhance the capacity of an ArrayList instance.

ensureCapacity(int

requiredCapacity)

E get(int index) It is used to fetch the element from the particular position of

the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

Iterator()

listIterator()

int It is used to return the index in this list of the last occurrence

lastIndexOf(Object of the specified element, or -1 if the list does not contain this

o) element.

Object[] toArray() It is used to return an array containing all of the elements in

this list in the correct order.


<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in

this list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean It returns true if the list contains the specified element.

contains(Object o)

int indexOf(Object o) It is used to return the index in this list of the first occurrence

of the specified element, or -1 if the List does not contain this

element.

E remove(int index) It is used to remove the element present at the specified

position in the list.

boolean It is used to remove the first occurrence of the specified

remove(Object o) element.
boolean It is used to remove all the elements from the list.

removeAll(Collection

<?> c)

boolean It is used to remove all the elements from the list that satisfies

removeIf(Predicate< the given predicate.

? super E> filter)

protected void It is used to remove all the elements lies within the given

removeRange(int range.

fromIndex, int

toIndex)

void It is used to replace all the elements from the list with the

replaceAll(UnaryOpe specified element.

rator<E> operator)

void It is used to retain all the elements in the list that are present

retainAll(Collection< in the specified collection.

?> c)
E set(int index, E It is used to replace the specified element in the list, present at

element) the specified position.

void It is used to sort the elements of the list on the basis of the

sort(Comparator<? specified comparator.

super E> c)

Spliterator<E> It is used to create a spliterator over the elements in a list.

spliterator()

List<E> subList(int It is used to fetch all the elements that lies within the given

fromIndex, int range.

toIndex)

int size() It is used to return the number of elements present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be

the list's current size.


Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in a collection. Now it
is type-safe, so typecasting is not required at runtime.

Let's see the old non-generic example of creating a Java collection.

1. ArrayList list=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have
the only specified type of object in it. If you try to add another type of object, it gives a
compile-time error.

import java.util.*;

public class ArrayListExample1{

public static void main(String args[]){

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

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Printing the arraylist object


System.out.println(list);

Iterating ArrayList using Iterator

import java.util.*;

public class ArrayListExample2{

public static void main(String args[]){

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

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through Iterator

Iterator itr=list.iterator();//getting the Iterator

while(itr.hasNext()){//check if iterator has the elements

System.out.println(itr.next());//printing the element and move to next

Iterating ArrayList using For-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop

FileName: ArrayListExample3.java

import java.util.*;

public class ArrayListExample3{

public static void main(String args[]){

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

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through for-each loop

for(String fruit:list)

System.out.println(fruit);

Get and Set ArrayList


The get() method returns the element at the specified index, whereas the set() method
changes the element.

How to Sort ArrayList

The java.util package provides a utility class Collections, which has the static method sort().
Using the Collections.sort() method, we can easily sort the ArrayList.

import java.util.*;

class SortArrayList{

public static void main(String args[]){

//Creating a list of fruits

List<String> list1=new ArrayList<String>();

list1.add("Mango");

list1.add("Apple");

list1.add("Banana");

list1.add("Grapes");

//Sorting the list

Collections.sort(list1);

//Traversing list through the for-each loop

for(String fruit:list1)

System.out.println(fruit);

System.out.println("Sorting numbers...");
//Creating a list of numbers

List<Integer> list2=new ArrayList<Integer>();

list2.add(21);

list2.add(11);

list2.add(51);

list2.add(1);

//Sorting the list

Collections.sort(list2);

//Traversing list through the for-each loop

for(Integer number:list2)

System.out.println(number);

Ways to iterate the elements of the collection in Java

There are various ways to traverse the collection elements:

1. By Iterator interface.

2. By for-each loop.

3. By ListIterator interface.

4. By for loop.

User-defined class objects in Java ArrayList


Let's see an example where we are storing Student class object in an array list.

class Student{

int rollno;

String name;

int age;

Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

—--------

import java.util.*;

class ArrayList5{

public static void main(String args[]){

//Creating user-defined class objects

Student s1=new Student(101,"Sonoo",23);

Student s2=new Student(102,"Ravi",21);

Student s2=new Student(103,"Hanumat",25);


//creating arraylist

ArrayList<Student> al=new ArrayList<Student>();

al.add(s1);//adding Student class object

al.add(s2);

al.add(s3);

//Getting Iterator

Iterator itr=al.iterator();

//traversing elements of ArrayList object

while(itr.hasNext()){

Student st=(Student)itr.next();

System.out.println(st.rollno+" "+st.name+" "+st.age);

Size and Capacity of an ArrayList

Size and capacity of an array list are the two terms that beginners find confusing. Let's
understand it in this section with the help of some examples. Consider the following code
snippet.

FileName: SizeCapacity.java
import java.util.*;

public class SizeCapacity

public static void main(String[] args) throws Exception

ArrayList<Integer> al = new ArrayList<Integer>();

System.out.println("The size of the array is: " + al.size());

Output:

The size of the array is: 0

Explanation: The output makes sense as we have not done anything with the array list. Now
observe the following program.

import java.util.*;

public class SizeCapacity1


{

public static void main(String[] args) throws Exception

ArrayList<Integer> al = new ArrayList<Integer>(10);

System.out.println("The size of the array is: " + al.size());

Output:

The size of the array is: 0

Explanation: We see that the size is still 0, and the reason behind this is the number 10
represents the capacity not the size. In fact, the size represents the total number of
elements present in the array. As we have not added any element, therefore, the size of the
array list is zero in both programs.

Capacity represents the total number of elements the array list can contain. Therefore, the
capacity of an array list is always greater than or equal to the size of the array list. When we
add an element to the array list, it checks whether the size of the array list has become equal
to the capacity or not. If yes, then the capacity of the array list increases. So, in the above
example, the capacity will be 10 till 10 elements are added to the list. When we add the 11th
element, the capacity increases. Note that in both examples, the capacity of the array list is
10. In the first case, the capacity is 10 because the default capacity of the array list is 10. In
the second case, we have explicitly mentioned that the capacity of the array list is 10.
LinkedList class

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

○ Java LinkedList class can contain duplicate elements.

○ Java LinkedList class maintains insertion order.

○ Java LinkedList class is non synchronized.

○ In Java LinkedList class, manipulation is fast because no shifting needs to occur.


○ Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class

As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class
and implements List and Deque interfaces.

Doubly Linked List

In the case of a doubly linked list, we can add or remove elements from both sides.

Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collec It is used to construct a list containing the elements of the

tion<? extends specified collection, in the order, they are returned by the

E> c) collection's iterator.


Methods of Java LinkedList

Method Description

boolean add(E e) It is used to append the specified element to the end of a list.

void add(int index, It is used to insert the specified element at the specified

E element) position index in a list.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean addAll(int It is used to append all the elements in the specified collection,

index, Collection<? starting at the specified position of the list.

extends E> c)
void addFirst(E e) It is used to insert the given element at the beginning of a list.

void addLast(E e) It is used to append the given element to the end of a list.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean It is used to return true if a list contains a specified element.

contains(Object o)

Iterator<E> It is used to return an iterator over the elements in a deque in

descendingIterator( reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position in a list.
E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object It is used to return the index in a list of the first occurrence of

o) the specified element, or -1 if the list does not contain any

element.

int It is used to return the index in a list of the last occurrence of

lastIndexOf(Object the specified element, or -1 if the list does not contain any

o) element.

ListIterator<E> It is used to return a list-iterator of the elements in proper

listIterator(int sequence, starting at the specified position in the list.

index)

boolean offer(E e) It adds the specified element as the last element of a list.
boolean offerFirst(E It inserts the specified element at the front of a list.

e)

boolean offerLast(E It inserts the specified element at the end of a list.

e)

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a list is

empty.

E peekLast() It retrieves the last element of a list or returns null if a list is

empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or returns

null if a list is empty.


E pollLast() It retrieves and removes the last element of a list, or returns null

if a list is empty.

E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a list.

E remove() It is used to retrieve and removes the first element of a list.

E remove(int index) It is used to remove the element at the specified position in a

list.

boolean It is used to remove the first occurrence of the specified

remove(Object o) element in a list.

E removeFirst() It removes and returns the first element from a list.


boolean It is used to remove the first occurrence of the specified

removeFirstOccurre element in a list (when traversing the list from head to tail).

nce(Object o)

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element in a list

removeLastOccurre (when traversing the list from head to tail).

nce(Object o)

E set(int index, E It replaces the element at the specified position in a list with

element) the specified element.

Object[] toArray() It is used to return an array containing all the elements in a list

in proper sequence (from first to the last element).

<T> T[] toArray(T[] It returns an array containing all the elements in the proper

a) sequence (from first to the last element); the runtime type of

the returned array is that of the specified array.


int size() It is used to return the number of elements in a list.

Java LinkedList Example


import java.util.*;

public class LinkedList1{

public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();

al.add("Ravi");

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

Iterator<String> itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

}
}

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain insertion order. Both
are non-synchronized classes.

However, there are many differences between the ArrayList and LinkedList classes that are
given below.

ArrayList LinkedList

1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly

store the elements. linked list to store the elements.

2) Manipulation with ArrayList is slow Manipulation with LinkedList is

because it internally uses an array. If any faster than ArrayList because it uses

element is removed from the array, all the a doubly linked list, so no bit shifting

other elements are shifted in memory. is required in memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and

because it implements List only. queue both because it implements

List and Deque interfaces.


4) ArrayList is better for storing and LinkedList is better for manipulating

accessing data. data.

5) The memory location for the elements of The location for the elements of a

an ArrayList is contiguous. linked list is not contagious.

6) Generally, when an ArrayList is initialized, a There is no case of default capacity

default capacity of 10 is assigned to the in a LinkedList. In LinkedList, an

ArrayList. empty list is created when a

LinkedList is initialized.

7) To be precise, an ArrayList is a resizable LinkedList implements the doubly

array. linked list of the list interface.

Points to Remember
The following are some important points to remember regarding an ArrayList and
LinkedList.

○ When the rate of addition or removal rate is more than the read scenarios, then go for
the LinkedList. On the other hand, when the frequency of the read scenarios is more
than the addition or removal rate, then ArrayList takes precedence over LinkedList.

○ Since the elements of an ArrayList are stored more compact as compared to a


LinkedList; therefore, the ArrayList is more cache-friendly as compared to the
LinkedList. Thus, chances for the cache miss are less in an ArrayList as compared to
a LinkedList. Generally, it is considered that a LinkedList is poor in cache-locality.

○ Memory overhead in the LinkedList is more as compared to the ArrayList. It is


because, in a LinkedList, we have two extra links (next and previous) as it is required
to store the address of the previous and the next nodes, and these links consume
extra space. Such links are not present in an ArrayList.

Java ListIterator Interface


ListIterator Interface is used to traverse the element in a backward and forward direction.

ListIterator Interface declaration


1. public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface:

Method Description

void add(E e) This method inserts the specified element into the list.

boolean This method returns true if the list iterator has more elements while

hasNext() traversing the list in the forward direction.

E next() This method returns the next element in the list and advances the

cursor position.
int This method returns the index of the element that would be returned

nextIndex() by a subsequent call to next()

boolean This method returns true if this list iterator has more elements while

hasPrevious( traversing the list in the reverse direction.

E previous() This method returns the previous element in the list and moves the

cursor position backward.

E This method returns the index of the element that would be returned

previousInde by a subsequent call to previous().

x()

void This method removes the last element from the list that was returned

remove() by next() or previous() methods

void set(E e) This method replaces the last element returned by next() or previous()

methods with the specified element.

Example of ListIterator Interface


import java.util.*;

public class ListIteratorExample1{


public static void main(String args[]){

List<String> al=new ArrayList<String>();

al.add("Amit");

al.add("Vijay");

al.add("Kumar");

al.add(1,"Sachin");

ListIterator<String> itr=al.listIterator();

System.out.println("Traversing elements in forward direction");

while(itr.hasNext()){

System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());

System.out.println("Traversing elements in backward direction");

while(itr.hasPrevious()){

System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());

}
Java HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

○ HashSet stores the elements by using a mechanism called hashing.


○ HashSet contains unique elements only.

○ HashSet allows null value.

○ HashSet class is non synchronized.

○ HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.

○ HashSet is the best approach for search operations.

○ The initial default capacity of HashSet is 16

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

Methods of Java HashSet class

Various methods of Java HashSet class are as follows:

SN Modi Method Description


fier
&
Type

1) boolea add(E e) It is used to add the specified element to this set if it is

n 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) boolea contains( It is used to return true if this set contains the specified

n Object o) element.

5) boolea isEmpty() It is used to return true if this set contains no elements.

6) Iterato iterator() It is used to return an iterator over the elements in this

r<E> set.

7) boolea remove(O It is used to remove the specified element from this set if

n bject o) it is present.

8) int size() It is used to return the number of elements in the set.

Java HashSet Example

Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.

import java.util.*;
class HashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet();

set.add("One");

set.add("Two");

set.add("Three");

set.add("Four");

set.add("Five");

Iterator<String> i=set.iterator();

while(i.hasNext())

System.out.println(i.next());

}
Java LinkedHashSet Class

Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set
interface. It inherits the HashSet class and implements the Set interface.

The important points about the Java LinkedHashSet class are:

○ Java LinkedHashSet class contains unique elements only like HashSet.

○ Java LinkedHashSet class provides all optional set operations and permits null
elements.

○ Java LinkedHashSet class is non-synchronized.

○ Java LinkedHashSet class maintains insertion order.


Note: Keeping the insertion order in the LinkedHashset has some additional costs, both in terms
of extra memory and extra CPU cycles. Therefore, if it is not required to maintain the insertion
order, go for the lighter-weight HashMap or the HashSet instead.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends the HashSet class, which implements the Set interface.
The Set interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet Class Declaration

Let's see the declaration for java.util.LinkedHashSet class.

1. public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable,


Serializable

Constructors of Java LinkedHashSet Class

Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(Collection c) It is used to initialize the hash set by using the elements of the

collection c.
LinkedHashSet(int It is used to initialize the capacity of the linked hash set to the

capacity) given integer value capacity.

LinkedHashSet(int It is used to initialize both the capacity and the fill ratio (also

capacity, float fillRatio) called load capacity) of the hash set from its argument.

Java LinkedHashSet Example

Let's see a simple example of the Java LinkedHashSet class. Here you can notice that the
elements iterate in insertion order.

FileName: LinkedHashSet1.java

import java.util.*;

class LinkedHashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

LinkedHashSet<String> set=new LinkedHashSet();

set.add("One");

set.add("Two");

set.add("Three");

set.add("Four");
set.add("Five");

Iterator<String> i=set.iterator();

while(i.hasNext())

System.out.println(i.next());

TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet
class are stored in ascending order.

The important points about the Java TreeSet class are:

○ Java TreeSet class contains unique elements only like HashSet.

○ Java TreeSet class access and retrieval times are quiet fast.

○ Java TreeSet class doesn't allow null element.

○ Java TreeSet class is non synchronized.

○ Java TreeSet class maintains ascending order.

○ The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer class.

Synchronization of The TreeSet Class

As already mentioned above, the TreeSet class is not synchronized. It means if more than
one thread concurrently accesses a tree set, and one of the accessing threads modify it,
then the synchronization must be done manually. It is usually done by doing some object
synchronization that encapsulates the set. However, in the case where no such object is
found, then the set must be wrapped with the help of the Collections.synchronizedSet()
method. It is advised to use the method during creation time in order to avoid the
unsynchronized access of the set. The following code snippet shows the same.

1. TreeSet treeSet = new TreeSet();

Hierarchy of TreeSet class


As shown in the above diagram, the Java TreeSet class implements the NavigableSet
interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable
interfaces in hierarchical order.

TreeSet Class Declaration

Let's see the declaration for java.util.TreeSet class.

1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>,


Cloneable, Serializable

Constructors of Java TreeSet Class

Constructor Description

TreeSet() It is used to construct an empty tree set that will be sorted in

ascending order according to the natural order of the tree set.

TreeSet(Collection<? It is used to build a new tree set that contains the elements of

extends E> c) the collection c.

TreeSet(Comparator<? It is used to construct an empty tree set that will be sorted

super E> comparator) according to given comparator.

TreeSet(SortedSet<E> It is used to build a TreeSet that contains the elements of the

s) given SortedSet.
Methods of Java TreeSet Class

Method Description

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

if it is not already present.

boolean addAll(Collection<? extends It is used to add all of the elements in the

E> c) specified collection to this set.

E ceiling(E e) It returns the equal or closest greatest element

of the specified element from the set, or null

there is no such element.

Comparator<? super E> comparator() It returns a comparator that arranges elements

in order.

Iterator descendingIterator() It is used to iterate the elements in descending

order.

NavigableSet descendingSet() It returns the elements in reverse order.


E floor(E e) It returns the equal or closest least element of

the specified element from the set, or null there

is no such element.

SortedSet headSet(E toElement) It returns the group of elements that are less

than the specified element.

NavigableSet headSet(E toElement, It returns the group of elements that are less

boolean inclusive) than or equal to(if, inclusive is true) the specified

element.

E higher(E e) It returns the closest greatest element of the

specified element from the set, or null there is no

such element.

Iterator iterator() It is used to iterate the elements in ascending

order.

E lower(E e) It returns the closest least element of the

specified element from the set, or null there is no

such element.
E pollFirst() It is used to retrieve and remove the lowest(first)

element.

E pollLast() It is used to retrieve and remove the highest(last)

element.

Spliterator spliterator() It is used to create a late-binding and fail-fast

spliterator over the elements.

NavigableSet subSet(E fromElement, It returns a set of elements that lie between the

boolean fromInclusive, E toElement, given range.

boolean toInclusive)

SortedSet subSet(E fromElement, E It returns a set of elements that lie between the

toElement)) given range which includes fromElement and

excludes toElement.

SortedSet tailSet(E fromElement) It returns a set of elements that are greater than

or equal to the specified element.


NavigableSet tailSet(E fromElement, It returns a set of elements that are greater than

boolean inclusive) or equal to (if, inclusive is true) the specified

element.

boolean contains(Object o) It returns true if this set contains the specified

element.

boolean isEmpty() It returns true if this set contains no elements.

boolean remove(Object o) It is used to remove the specified element from

this set if it is present.

void clear() It is used to remove all of the elements from this

set.

Object clone() It returns a shallow copy of this TreeSet

instance.

E first() It returns the first (lowest) element currently in

this sorted set.


E last() It returns the last (highest) element currently in

this sorted set.

int size() It returns the number of elements in this set.

Java TreeSet Examples

Java TreeSet Example 1:

Let's see a simple example of Java TreeSet.

FileName: TreeSet1.java

import java.util.*;

class TreeSet1{

public static void main(String args[]){

//Creating and adding elements

TreeSet<String> al=new TreeSet<String>();

al.add("Ravi");

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

//Traversing elements
Iterator<String> itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

—-----

import java.util.*;

class TreeSet3{

public static void main(String args[]){

TreeSet<Integer> set=new TreeSet<Integer>();

set.add(24);

set.add(66);

set.add(12);

set.add(15);

System.out.println("Lowest Value: "+set.pollFirst());

System.out.println("Highest Value: "+set.pollLast());

}
Java Vector
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 a part of Java Collection framework
since Java 1.2. It is found in the java.util package and implements the List interface, so we
can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you
don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList
will perform better in such case.

ava Vector Constructors

Vector class supports four types of constructors. These are given below:

S Constructor Description
N

1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initial

capacity and with its capacity increment equal to zero.

3) vector(int initialCapacity, It constructs an empty vector with the specified initial

int capacityIncrement) capacity and capacity increment.


4) Vector( Collection<? It constructs a vector that contains the elements of a

extends E> c) collection c.

Java Vector Methods

The following are the list of Vector class methods:

S Method Description
N

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to

the end of this Vector.

3) addElement() It is used to append the specified component to the end of 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.

8) containsAll() It returns true if the vector contains all of the elements in the

specified collection.

9) copyInto() It is used to copy the components of the vector into the specified

array.

1 elementAt() It is used to get the component at the specified index.

0)

1 elements() It returns an enumeration of the components of a vector.

1)

1 ensureCapac It is used to increase the capacity of the vector which is in use, if

2) ity() necessary. It ensures that the vector can hold at least the number of

components specified by the minimum capacity argument.

1 equals() It is used to compare the specified object with the vector for equality.

3)
1 firstElement() It is used to get the first component of the vector.

4)

1 forEach() It is used to perform the given action for each element of the Iterable

5) until all elements have been processed or the action throws an

exception.

1 get() It is used to get an element at the specified position in the vector.

6)

1 hashCode() It is used to get the hash code value of a vector.

7)

1 indexOf() It is used to get the index of the first occurrence of the specified

8) element in the vector. It returns -1 if the vector does not contain the

element.

1 insertElemen It is used to insert the specified object as a component in the given

9) tAt() vector at the specified index.

2 isEmpty() It is used to check if this vector has no components.

0)
2 iterator() It is used to get an iterator over the elements in the list in proper

1) sequence.

2 lastElement() It is used to get the last component of the vector.

2)

2 lastIndexOf() It is used to get the index of the last occurrence of the specified

3) element in the vector. It returns -1 if the vector does not contain the

element.

2 listIterator() It is used to get a list iterator over the elements in the list in proper

4) sequence.

2 remove() It is used to remove the specified element from the vector. If the

5) vector does not contain the element, it is unchanged.

2 removeAll() It is used to delete all the elements from the vector that are present in

6) the specified collection.

2 removeAllEle It is used to remove all elements from the vector and set the size of

7) ments() the vector to zero.


2 removeEleme It is used to remove the first (lowest-indexed) occurrence of the

8) nt() argument from the vector.

2 removeEleme It is used to delete the component at the specified index.

9) ntAt()

3 removeIf() It is used to remove all of the elements of the collection that satisfy

0) the given predicate.

3 removeRang It is used to delete all of the elements from the vector whose index is

1) e() between fromIndex, inclusive and toIndex, exclusive.

3 replaceAll() It is used to replace each element of the list with the result of

2) applying the operator to that element.

3 retainAll() It is used to retain only that element in the vector which is contained

3) in the specified collection.

3 set() It is used to replace the element at the specified position in the vector

4) with the specified element.


3 setElementAt It is used to set the component at the specified index of the vector to

5) () the specified object.

3 setSize() It is used to set the size of the given vector.

6)

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

7)

3 sort() It is used to sort the list according to the order induced by the

8) specified Comparator.

3 spliterator() It is used to create a late-binding and fail-fast Spliterator over the

9) elements in the list.

4 subList() It is used to get a view of the portion of the list between fromIndex,

0) inclusive, and toIndex, exclusive.

4 toArray() It is used to get an array containing all of the elements in this vector

1) in correct order.
4 toString() It is used to get a string representation of the vector.

2)

4 trimToSize() It is used to trim the capacity of the vector to the vector's current size.

3)

Java Vector Example


import java.util.*;

public class VectorExample {

public static void main(String args[]) {

//Create a vector

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

//Adding elements using add() method of List

vec.add("Tiger");

vec.add("Lion");

vec.add("Dog");

vec.add("Elephant");

//Adding elements using addElement() method of Vector

vec.addElement("Rat");
vec.addElement("Cat");

vec.addElement("Deer");

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

Java Stack
The stack is a linear data structure that is used to store the collection of objects. It is based
on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and
classes to store the collection of objects. One of them is the Stack class that provides
different operations such as push, pop, search, etc.

In this section, we will discuss the Java Stack class, its methods, and implement the stack
data structure in a Java program. But before moving to the Java Stack class have a quick
view of how the stack works.

The stack data structure has the two most important operations that are push and pop. The
push operation inserts an element into the stack and pop operation removes an element
from the top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

Let's remove (pop) 18, 45, and 11 from the stack.


Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following figure,

○ Push 12, top=0

○ Push 6, top=1

○ Push 9, top=2
When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9.
The following table shows the different values of the top.

Java Stack Class


In Java, Stack is a class that falls under the Collection framework that extends the Vector
class. It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It
represents the LIFO stack of objects. Before using the Stack class, we must import the
java.util package. The stack class arranged in the Collections framework hierarchy, as
shown below.
Stack Class Constructor
The Stack class contains only the default constructor that creates an empty stack.

1. public Stack()

Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of the
Stack class.

1. Stack stk = new Stack();


Or

1. Stack<type> stk = new Stack<>();

Where type denotes the type of stack like Integer, String, etc.

Methods of the Stack Class


We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides
all the methods of the Java Vector class.

Metho Modifie Method Description


d r and
Type

empty() boolean The method checks the stack is empty or not.

push(E E The method pushes (insert) an element onto the top of the stack.

item)

pop() E The method removes an element from the top of the stack and

returns the same element as the value of that function.

peek() E The method looks at the top element of the stack without

removing it.
search(O int The method searches the specified object and returns the

bject o) position of the object.

Stack Class empty() Method

The empty() method of the Stack class check the stack is empty or not. If the stack is
empty, it returns true, else returns false. We can also use the isEmpty() method of the Vector
class.

Syntax

1. public boolean empty()

Returns: The method returns true if the stack is empty, else returns false.

In the following example, we have created an instance of the Stack class. After that, we have
invoked the empty() method two times. The first time it returns true because we have not
pushed any element into the stack. After that, we have pushed elements into the stack.
Again we have invoked the empty() method that returns false because the stack is not
empty.

StackEmptyMethodExample.java

1. import java.util.Stack;
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = stk.empty();
10. System.out.println("Is the stack empty? " + result);
11. // pushing elements into stack
12. stk.push(78);
13. stk.push(113);
14. stk.push(90);
15. stk.push(120);
16. //prints elements of the stack
17. System.out.println("Elements in Stack: " + stk);
18. result = stk.empty();
19. System.out.println("Is the stack empty? " + result);
20. }
21. }

Output:

Is the stack empty? true

Elements in Stack: [78, 113, 90, 120]

Is the stack empty? false

Stack Class push() Method

The method inserts an item onto the top of the stack. It works the same as the method
addElement(item) method of the Vector class. It passes a parameter item to be pushed into
the stack.

Syntax

1. public E push(E item)


Parameter: An item to be pushed onto the top of the stack.

Returns: The method returns the argument that we have passed as a parameter.

Stack Class pop() Method

The method removes an object at the top of the stack and returns the same object. It throws
EmptyStackException if the stack is empty.

Syntax

1. public E pop()

Returns: It returns an object that is at the top of the stack.

Let's implement the stack in a Java program and perform push and pop operations.

StackPushPopExample.java

1. import java.util.*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. System.out.println("stack: " + stk);
9. //pushing elements into the stack
10. pushelmnt(stk, 20);
11. pushelmnt(stk, 13);
12. pushelmnt(stk, 89);
13. pushelmnt(stk, 90);
14. pushelmnt(stk, 11);
15. pushelmnt(stk, 45);
16. pushelmnt(stk, 18);
17. //popping elements from the stack
18. popelmnt(stk);
19. popelmnt(stk);
20. //throws exception if the stack is empty
21. try
22. {
23. popelmnt(stk);
24. }
25. catch (EmptyStackException e)
26. {
27. System.out.println("empty stack");
28. }
29. }
30. //performing push operation
31. static void pushelmnt(Stack stk, int x)
32. {
33. //invoking push() method
34. stk.push(new Integer(x));
35. System.out.println("push -> " + x);
36. //prints modified stack
37. System.out.println("stack: " + stk);
38. }
39. //performing pop operation
40. static void popelmnt(Stack stk)
41. {
42. System.out.print("pop -> ");
43. //invoking pop() method
44. Integer x = (Integer) stk.pop();
45. System.out.println(x);
46. //prints modified stack
47. System.out.println("stack: " + stk);
48. }
49. }

Output:

stack: []

push -> 20

stack: [20]

push -> 13

stack: [20, 13]

push -> 89

stack: [20, 13, 89]

push -> 90

stack: [20, 13, 89, 90]

push -> 11

stack: [20, 13, 89, 90, 11]

push -> 45

stack: [20, 13, 89, 90, 11, 45]

push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]

pop -> 18

stack: [20, 13, 89, 90, 11, 45]

pop -> 45

stack: [20, 13, 89, 90, 11]

pop -> 11

stack: [20, 13, 89, 90]

Stack Class peek() Method

It looks at the element that is at the top in the stack. It also throws EmptyStackException if
the stack is empty.

Syntax

1. public E peek()

Returns: It returns the top elements of the stack.

Let's see an example of the peek() method.

StackPeekMethodExample.java

1. import java.util.Stack;
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. stk.push("Apple");
9. stk.push("Grapes");
10. stk.push("Mango");
11. stk.push("Orange");
12. System.out.println("Stack: " + stk);
13. // Access element from the top of the stack
14. String fruits = stk.peek();
15. //prints stack
16. System.out.println("Element at top: " + fruits);
17. }
18. }

Output:

Stack: [Apple, Grapes, Mango, Orange]

Element at the top of the stack: Orange

Stack Class search() Method

The method searches the object in the stack from the top. It parses a parameter that we
want to search for. It returns the 1-based location of the object in the stack. Thes topmost
object of the stack is considered at distance 1.

Suppose, o is an object in the stack that we want to search for. The method returns the
distance from the top of the stack of the occurrence nearest the top of the stack. It uses
equals() method to search an object in the stack.
Syntax

1. public int search(Object o)

Parameter: o is the desired object to be searched.

Returns: It returns the object location from the top of the stack. If it returns -1, it means that
the object is not on the stack.

Let's see an example of the search() method.

StackSearchMethodExample.java

1. import java.util.Stack;
2. public class StackSearchMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. //pushing elements into Stack
8. stk.push("Mac Book");
9. stk.push("HP");
10. stk.push("DELL");
11. stk.push("Asus");
12. System.out.println("Stack: " + stk);
13. // Search an element
14. int location = stk.search("HP");
15. System.out.println("Location of Dell: " + location);
16. }
17. }
Java Stack Operations

Size of the Stack

We can also find the size of the stack using the size() method of the Vector class. It returns
the total number of elements (size of the stack) in the stack.

Syntax

1. public int size()

Let's see an example of the size() method of the Vector class.

StackSizeExample.java

1. import java.util.Stack;
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. stk.push(22);
8. stk.push(33);
9. stk.push(44);
10. stk.push(55);
11. stk.push(66);
12. // Checks the Stack is empty or not
13. boolean rslt=stk.empty();
14. System.out.println("Is the stack empty or not? " +rslt);
15. // Find the size of the Stack
16. int x=stk.size();
17. System.out.println("The stack size is: "+x);
18. }
19. }

Output:

Is the stack empty or not? false

The stack size is: 5

Iterate Elements

Iterate means to fetch the elements of the stack. We can fetch elements of the stack using
three different methods are as follows:

○ Using iterator() Method

○ Using forEach() Method

○ Using listIterator() Method

Using the iterator() Method

It is the method of the Iterator interface. It returns an iterator over the elements in the stack.
Before using the iterator() method import the java.util.Iterator package.

Syntax

1. Iterator<T> iterator()

Let's perform an iteration over the stack.

StackIterationExample1.java

1. import java.util.Iterator;
import java.util.Stack;

public class StackIterationExample1

public static void main (String[] args)

//creating an object of Stack class

Stack stk = new Stack();

//pushing elements into stack

stk.push("BMW");

stk.push("Audi");

stk.push("Ferrari");

stk.push("Bugatti");

stk.push("Jaguar");

//iteration over the stack

Iterator iterator = stk.iterator();

while(iterator.hasNext())

Object values = iterator.next();

System.out.println(values);
}

2. }

Output:

BMW

Audi

Ferrari

Bugatti

Jaguar

Using the forEach() Method

Java provides a forEach() method to iterate over the elements. The method is defined in the
Iterable and Stream interface.

Syntax

1. default void forEach(Consumer<super T>action)

Let's iterate over the stack using the forEach() method.

StackIterationExample2.java

import java.util.*;

public class StackIterationExample2


{

public static void main (String[] args)

//creating an instance of Stack class

Stack <Integer> stk = new Stack<>();

//pushing elements into stack

stk.push(119);

stk.push(203);

stk.push(988);

System.out.println("Iteration over the stack using forEach() Method:");

//invoking forEach() method for iteration over the stack

stk.forEach(n ->

System.out.println(n);

});

Output:

Iteration over the stack using forEach() Method:


119

203

988

Using listIterator() Method

This method returns a list iterator over the elements in the mentioned list (in sequence),
starting at the specified position in the list. It iterates the stack from top to bottom.

Syntax

1. ListIterator listIterator(int index)

Parameter: The method parses a parameter named index.

Returns: This method returns a list iterator over the elements, in sequence.

Exception: It throws IndexOutOfBoundsException if the index is out of range.

Let's iterate over the stack using the listIterator() method.

StackIterationExample3.java

import java.util.Iterator;

import java.util.ListIterator;

import java.util.Stack;

public class StackIterationExample3


{

public static void main (String[] args)

Stack <Integer> stk = new Stack<>();

stk.push(119);

stk.push(203);

stk.push(988);

ListIterator<Integer> ListIterator = stk.listIterator(stk.size());

System.out.println("Iteration over the Stack from top to bottom:");

while (ListIterator.hasPrevious())

Integer avg = ListIterator.previous();

System.out.println(avg);

Java Deque Interface


The interface called Deque is present in java.util package. It is the subtype of the interface
queue. The Deque supports the addition as well as the removal of elements from both ends
of the data structure. Therefore, a deque can be used as a stack or a queue. We know that
the stack supports the Last In First Out (LIFO) operation, and the operation First In First Out
is supported by a queue. As a deque supports both, either of the mentioned operations can
be performed on it. Deque is an acronym for "double ended queue".

Deque Interface declaration


1. public interface Deque<E> extends Queue<E>

Methods of Java Deque Interface

Metho Description
d

boolean It is used to insert the specified element into this deque and return true upon

add(obje success.

ct)

boolean It is used to insert the specified element into this deque.

offer(obj

ect)
Object It is used to retrieve and removes the head of this deque.

remove(

Object It is used to retrieve and removes the head of this deque, or returns null if this

poll() deque is empty.

Object It is used to retrieve, but does not remove, the head of this deque.

element(

Object It is used to retrieve, but does not remove, the head of this deque, or returns

peek() null if this deque is empty.

Object The method returns the head element of the deque. The method does not

peekFirs remove any element from the deque. Null is returned by this method, when the

t() deque is empty.

Object The method returns the last element of the deque. The method does not

peekLas remove any element from the deque. Null is returned by this method, when the

t() deque is empty.


Boolean Inserts the element e at the front of the queue. If the insertion is successful,

offerFirs true is returned; otherwise, false.

t(e)

Object Inserts the element e at the tail of the queue. If the insertion is successful, true

offerLas is returned; otherwise, false.

t(e)

ArrayDeque class
We know that it is not possible to create an object of an interface in Java. Therefore, for
instantiation, we need a class that implements the Deque interface, and that class is
ArrayDeque. It grows and shrinks as per usage. It also inherits the AbstractCollection class.

The important points about ArrayDeque class are:

○ Unlike Queue, we can add or remove elements from both sides.

○ Null elements are not allowed in the ArrayDeque.

○ ArrayDeque is not thread safe, in the absence of external synchronization.

○ ArrayDeque has no capacity restrictions.

○ ArrayDeque is faster than LinkedList and Stack.

ArrayDeque Hierarchy

The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the
page.

ArrayDeque class declaration

Let's see the declaration for java.util.ArrayDeque class.

1. public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>,


Cloneable, Serializable

Java ArrayDeque Example

FileName: ArrayDequeExample.java

import java.util.*;

public class ArrayDequeExample {


public static void main(String[] args) {

//Creating Deque and adding elements

Deque<String> deque = new ArrayDeque<String>();

deque.add("Ravi");

deque.add("Vijay");

deque.add("Ajay");

//Traversing elements

for (String str : deque) {

System.out.println(str);

Output:

Ravi

Vijay

Ajay

Java ArrayDeque Example: offerFirst() and pollLast()

FileName: DequeExample.java
import java.util.*;

public class DequeExample {

public static void main(String[] args) {

Deque<String> deque=new ArrayDeque<String>();

deque.offer("arvind");

deque.offer("vimal");

deque.add("mukul");

deque.offerFirst("jai");

System.out.println("After offerFirst Traversal...");

for(String s:deque){

System.out.println(s);

//deque.poll();

//deque.pollFirst();//it is same as poll()

deque.pollLast();

System.out.println("After pollLast() Traversal...");

for(String s:deque){

System.out.println(s);

}
}

Output:

After offerFirst Traversal...

jai

arvind

vimal

mukul

After pollLast() Traversal...

jai

arvind

vimal

Java ArrayDeque Example: Book

FileName: ArrayDequeExample.java

import java.util.*;

class Book {

int id;

String name,author,publisher;
int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

this.id = id;

this.name = name;

this.author = author;

this.publisher = publisher;

this.quantity = quantity;

public class ArrayDequeExample {

public static void main(String[] args) {

Deque<Book> set=new ArrayDeque<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw


Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to Deque

set.add(b1);
set.add(b2);

set.add(b3);

//Traversing ArrayDeque

for(Book b:set){

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

}
z
PS1 Diagnostics

Notes:
• Go through The Problem Statement Completely
• Time Allowed is 90 minutes
• Make sure your project is created in Eclipse only
• Create all your java files in the com package.
• Make sure that the exact class outline is followed.
• You need to zip the eclipse project folder and upload the same in LMS once completed
• It is mandatory to upload eclipse project and not only java files for your code to be assessed.
• Make sure that there is no compilation error in your code before submission. Even if there is
minor error, entire solution could be rejected

Problem Statement:

Thomas Travels wants to collect and automate their customer travel service process. Each driver in
the thomas travels has following attributes.

1. Id of the driver
2. Name of the driver
3. Category of the driver (Auto/Car/Lorry)
4. Total distance he traveled

Create a class called Driver as shown below:


Create a class called Travel as shown below:

• isCarDriver (Driver) : This method will check whether the given Driver class object is
belonging to the category “Car”. It will return true if the given Driver object is of category
“Car” else return false.
• RetrivebyDriverId (ArrayList<Driver>,driverID) : This method will search the given
driverId in the arraylist and returns the String in the following format

Driver name is <driverName> Belonging to the category <category> traveled <


totalDistance> KM so far.

Example:
Driver name is Sudhagar belonging to the category Car traveled 4200 KM so far.

• RetriveCountOfDriver (ArrayList<Driver>,String) : This method will category of


driver and an arraylist of driver as input and search for an category and returns the
count of drivers.

• retriveDriver (ArrayList<Driver>,String) : This method will category of driver and an


arraylist of driver as input and search for an category. and drivers who are belonging to that
category should be return as a array list.

• RetriveMaximumDistanceTravelledDriver (ArrayList<Driver>) : This method will


return the driver who traveled maximum distance

Create a Tester Class called TestDriver with a main method in order to test the above methods
using Driver objects.

All the best!!


1. What are the major new features introduced in Java 8?

Java 8 introduced several key features, such as Lambda Expressions, the Stream API, default
methods in interfaces, the new Date-Time API, and the Optional class. These features have
significantly changed the way Java is written and used, emphasizing a more functional style of
programming.

2. Explain Lambda Expressions in Java 8.

Lambda Expressions are a new feature that enables treating functionality as a method
argument or code as data. A lambda expression is like a method: it provides a list of parameters
and a body (expressed in terms of these parameters) which is executed when the lambda
expression is invoked.

3. What is the Stream API in Java 8?

The Stream API is a new abstraction that lets you process sequences of elements (like
collections) in a functional style. It supports operations like map, filter, limit, reduce, find, match,
and so on, and can be executed in serial or parallel.

4. How are default methods in interfaces useful in Java 8?

Default methods in interfaces allow the interfaces to have methods with implementation without
breaking the existing implementation of classes. This was introduced mainly to provide
backward compatibility for old interfaces when new methods are added to them.

5. What is the Optional class in Java 8?

Optional is a container object which may or may not contain a non-null value. It's used to
represent the idea of computation that might fail, and it helps in avoiding null checks and
NullPointerException.

6. Explain the difference between intermediate and terminal operations in the Stream API.

Intermediate operations return a new Stream and are lazy, meaning they don't start processing
the content until the terminal operation is invoked. Terminal operations, on the other hand,
produce a non-stream result, such as a primitive value, a collection, or nothing, and process the
stream data.

1
7. How does the forEach() method differ from a traditional for loop?

The forEach() method is an internal iterator that abstracts the process of iterating, allowing the
Stream API to control the iteration. In contrast, a traditional for loop is an external iterator where
the user controls the iteration explicitly.

8. What is the purpose of the Collectors class in Java 8?

The Collectors class in the java.util.stream package is a utility class that provides common
reduction operations, such as accumulating elements into collections, summarizing elements
according to various criteria, etc.

9. What is a functional interface in Java 8?

A functional interface in Java 8 is an interface that has exactly one abstract method. These
interfaces can be used as the types on which lambda expressions are declared. Common
examples include java.util.function.Predicate, java.util.function.Function, and
java.util.function.Consumer.

10. Describe the new Date-Time API in Java 8.

Java 8 introduced a new Date-Time API under the java.time package. It fixes the design flaws of
the old date-time APIs (java.util.Date, java.util.Calendar) and provides immutable, thread-safe
date-time classes, and more intuitive methods to manipulate dates, times, durations, and
periods.

You might also like