D2 JDK Jre JVM
D2 JDK Jre JVM
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.
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 - //
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0
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;
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);
}
}
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..
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 less than or equal to right side.
Ternary Operator
This operator evaluates a boolean expression and assign the value based on
the result.
Syntax:
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.
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.
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 {
}
}
}
First step: In for loop, initialization happens first and only one time, which
means that the initialization part of for loop only executes once.
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.
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]);
}
}
}
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);
}
}
}
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.
Syntax:
continue word followed by semi colon.
continue;
System.out.print(j+" ");
}
}
}
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.
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.
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.
2)Through Constructor.
These variables are also declared inside a class but not inside any method or block.
The major difference with static and non static variables is the Memory allocation.
Syntax: ClassName.variableName
In our day to day programming , we use static when the variable should be constant in entire
application.
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?
1)Static Method
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.
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
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.
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
Abstraction:-
There are two types of methods in java based on signature.
a. Normal methods
b. Abstract methods
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;
...
String city,state,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.
class Car {
public Car() {
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 {
public University() {
students.add(student);
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.
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.
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;
Syntax:-
try
{ risky code;
}
catch (Exception obj)
{ handling code;
}
finally
{ Clean-up code;(database connection closing, streams closing……etc)
}
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.
=========================================
A thread can be created in two ways:-
1) By extending Thread class.
2) By implementing java.lang.Runnable interface.
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.
2)Ready :- t.start()
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”.
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.
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
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;
M1 m1 = new M1();
m1.s1 = s;
M2 m2 = new M2();
m2.s1 = s;
m1.start();
m2.start();
}
SourceTable s1;
@Override
public void run() {
s1.tablePrint(5);
SourceTable s1;
@Override
public void run() {
s1.tablePrint(10);
Source table:
package sync;
For Synchronization.
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.
I.e : remaining threads can execute normal static methods, normal instance
methods.
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.
Method Description
public final Class returns the Class class object of this object. The Class
class.
public int hashCode() returns the hashcode number for this object.
equals(Object obj)
protected Object clone() creates and returns the exact copy (clone) of this object.
throws
CloneNotSupportedExcept
ion
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
public final void wait(long causes the current thread to wait for the specified
public final void causes the current thread to wait, until another thread
InterruptedException
1. By string literal
2. By new keyword
1) String Literal
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";
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".
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
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 ?
a)indexOf
b)charAt
d)replace()
e)toUpperCase()
f)toLowerCase()
g)split();
h)replace();
i)equals
j)equalsIgnoreCase()
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:
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.
○ 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.
○ 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
int a=20;
}}
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.
}}
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.
collection.
E> c)
collection.
E> filter)
collection.
the collection.
contains(Object element)
10 public boolean It is used to search the specified collection in
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
specified array.
element)
collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction
only.
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
2 public Object next() It returns the element and moves the cursor pointer to the
next element.
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.
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.
○ 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:
○ 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(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
boolean add(E e) It is used to append the specified element at the end of a list.
addAll(Collection<? collection to the end of this list, in the order that they are
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.
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.
contains(Object o)
int indexOf(Object o) It is used to return the index in this list of the first occurrence
element.
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
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
rator<E> operator)
void It is used to retain all the elements in the list that are present
?> c)
E set(int index, E It is used to replace the specified element in the list, present at
void It is used to sort the elements of the list on the basis of the
super E> c)
spliterator()
List<E> subList(int It is used to fetch all the elements that lies within the given
toIndex)
int size() It is used to return the number of elements present in the list.
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.
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.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
FileName: ArrayListExample3.java
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
for(String fruit:list)
System.out.println(fruit);
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{
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
Collections.sort(list1);
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
Collections.sort(list2);
for(Integer number:list2)
System.out.println(number);
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
class Student{
int rollno;
String name;
int age;
this.rollno=rollno;
this.name=name;
this.age=age;
—--------
import java.util.*;
class ArrayList5{
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
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.*;
Output:
Explanation: The output makes sense as we have not done anything with the array list. Now
observe the following program.
import java.util.*;
Output:
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.
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class
and implements List and Deque interfaces.
In the case of a doubly linked list, we can add or remove elements from both sides.
Constructor Description
tion<? extends specified collection, in the order, they are returned by the
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
addAll(Collection<? collection to the end of this list, in the order that they are
addAll(Collection<? collection to the end of this list, in the order that they are
boolean addAll(int It is used to append all the elements in the specified collection,
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.
contains(Object o)
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.
int indexOf(Object It is used to return the index in a list of the first occurrence of
element.
lastIndexOf(Object the specified element, or -1 if the list does not contain any
o) element.
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)
e)
empty.
empty.
if a list is empty.
list.
removeFirstOccurre element in a list (when traversing the list from head to tail).
nce(Object o)
nce(Object o)
E set(int index, E It replaces the element at the specified position in a list with
Object[] toArray() It is used to return an array containing all the elements in a list
<T> T[] toArray(T[] It returns an array containing all the elements in the proper
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());
}
}
However, there are many differences between the ArrayList and LinkedList classes that are
given below.
ArrayList LinkedList
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
3) An ArrayList class can act as a list only LinkedList class can act as a list and
5) The memory location for the elements of The location for the elements of a
LinkedList is initialized.
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.
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
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
boolean This method returns true if this list iterator has more elements while
E previous() This method returns the previous element in the list and moves the
E This method returns the index of the element that would be returned
x()
void This method removes the last element from the list that was returned
void set(E e) This method replaces the last element returned by next() or previous()
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
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.
○ HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.
A list can contain duplicate elements whereas Set contains unique elements only.
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
4) boolea contains( It is used to return true if this set contains the specified
n Object o) element.
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.
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.
import java.util.*;
class HashSet1{
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.
○ Java LinkedHashSet class provides all optional set operations and permits null
elements.
The LinkedHashSet class extends the HashSet class, which implements the Set interface.
The Set interface inherits Collection and Iterable interfaces in hierarchical order.
Constructor Description
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
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.
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{
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.
○ Java TreeSet class access and retrieval times are quiet fast.
○ The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer 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.
Constructor Description
TreeSet(Collection<? It is used to build a new tree set that contains the elements of
s) given SortedSet.
Methods of Java TreeSet Class
Method Description
in order.
order.
is no such element.
SortedSet headSet(E toElement) It returns the group of elements that are less
NavigableSet headSet(E toElement, It returns the group of elements that are less
element.
such element.
order.
such element.
E pollFirst() It is used to retrieve and remove the lowest(first)
element.
element.
NavigableSet subSet(E fromElement, It returns a set of elements that lie between the
boolean toInclusive)
SortedSet subSet(E fromElement, E It returns a set of elements that lie between the
excludes toElement.
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than
element.
element.
set.
instance.
FileName: TreeSet1.java
import java.util.*;
class TreeSet1{
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{
set.add(24);
set.add(66);
set.add(12);
set.add(15);
}
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.
Vector class supports four types of constructors. These are given below:
S Constructor Description
N
S Method Description
N
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.
0)
1)
2) ity() necessary. It ensures that the vector can hold at least the number of
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
exception.
6)
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.
0)
2 iterator() It is used to get an iterator over the elements in the list in proper
1) sequence.
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
2 removeAll() It is used to delete all the elements from the vector that are present in
2 removeAllEle It is used to remove all elements from the vector and set the size of
9) ntAt()
3 removeIf() It is used to remove all of the elements of the collection that satisfy
3 removeRang It is used to delete all of the elements from the vector whose index is
3 replaceAll() It is used to replace each element of the list with the result of
3 retainAll() It is used to retain only that element in the vector which is contained
3 set() It is used to replace the element at the specified position in the vector
6)
7)
3 sort() It is used to sort the list according to the order induced by the
8) specified Comparator.
4 subList() It is used to get a view of the portion of the list between fromIndex,
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)
//Create a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
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.
○ 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.
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.
Where type denotes the type of stack like Integer, String, etc.
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
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
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
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:
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
Returns: The method returns the argument that we have passed as a parameter.
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()
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
push -> 89
push -> 90
push -> 11
push -> 45
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
pop -> 45
pop -> 11
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()
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:
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
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.
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
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
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:
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:
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()
StackIterationExample1.java
1. import java.util.Iterator;
import java.util.Stack;
stk.push("BMW");
stk.push("Audi");
stk.push("Ferrari");
stk.push("Bugatti");
stk.push("Jaguar");
while(iterator.hasNext())
System.out.println(values);
}
2. }
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar
Java provides a forEach() method to iterate over the elements. The method is defined in the
Iterable and Stream interface.
Syntax
StackIterationExample2.java
import java.util.*;
stk.push(119);
stk.push(203);
stk.push(988);
stk.forEach(n ->
System.out.println(n);
});
Output:
203
988
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
Returns: This method returns a list iterator over the elements, in sequence.
StackIterationExample3.java
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;
stk.push(119);
stk.push(203);
stk.push(988);
while (ListIterator.hasPrevious())
System.out.println(avg);
Metho Description
d
boolean It is used to insert the specified element into this deque and return true upon
add(obje success.
ct)
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
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
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
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(e)
Object Inserts the element e at the tail of the queue. If the insertion is successful, true
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.
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the
page.
FileName: ArrayDequeExample.java
import java.util.*;
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
System.out.println(str);
Output:
Ravi
Vijay
Ajay
FileName: DequeExample.java
import java.util.*;
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
for(String s:deque){
System.out.println(s);
//deque.poll();
deque.pollLast();
for(String s:deque){
System.out.println(s);
}
}
Output:
jai
arvind
vimal
mukul
jai
arvind
vimal
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;
//Creating Books
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing ArrayDeque
for(Book b:set){
}
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
• 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
Example:
Driver name is Sudhagar belonging to the category Car traveled 4200 KM so far.
Create a Tester Class called TestDriver with a main method in order to test the above methods
using Driver objects.
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.
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.
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.
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.
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.
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.
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.
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.