0% found this document useful (0 votes)
11 views82 pages

Java Fundamentals: Concepts and Structures

The document covers various Java programming concepts including memory management, object creation, access modifiers, data types, and principles of object-oriented programming such as inheritance, encapsulation, and polymorphism. It also discusses the differences between JVM, JDK, and JRE, as well as the usage of static and final keywords, and the importance of immutability in wrapper classes. Additionally, it touches on advanced topics like recursion, call by value vs. call by reference, and the strictfp keyword for consistent floating-point calculations.

Uploaded by

just.start0101
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)
11 views82 pages

Java Fundamentals: Concepts and Structures

The document covers various Java programming concepts including memory management, object creation, access modifiers, data types, and principles of object-oriented programming such as inheritance, encapsulation, and polymorphism. It also discusses the differences between JVM, JDK, and JRE, as well as the usage of static and final keywords, and the importance of immutability in wrapper classes. Additionally, it touches on advanced topics like recursion, call by value vs. call by reference, and the strictfp keyword for consistent floating-point calculations.

Uploaded by

just.start0101
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

====================

P - Static block
C - Static block

P - Initialisation block
P - Constructor

C - Initialisation block
C - Constructor

===============

8 - 2014. - this one


9 - 2017
10 , 11 - 2018
12 , 13 - 2019
14 , 15 - 2020
16 , 17 - 2021
18 , 19 - 2022
20, 21 - 2023 - This one - 21
22 , 23 - 2024

==================

.Class - Platform independent


.Java -

Compiler -
Interceptor -

JVM -
JRE -
JDK -

=====================

Path VS class path

PATH = C:\Program Files\Java\jdk-21\bin;

.class - CLASSPATH = C:\myprojects\lib\[Link];C:\myprojects\classes;

======

How many ways you can write main method in java -

=============

JVm VS JDK
JVM -

Load Code.
Memomey allocation -

Class. - store class-level data, including class structures, method information, and static
variables.

Heap - Used to store objects created , All objects and their associated instance variables. ,
he actual data for class elds that belong to objects. — GC -

Stack - used to store objects reference


Method call information (parameters, return addresses).
Local variables of methods (primitives or references to objects in the heap).
The current execution point of methods (control ow).
LIFO - last in rst out
Register -
CPU instructions and operands for calculations.
Memory addresses for data fetch/store operations.
What It Is: Registers are small, fast storage areas located inside the CPU. They store data that
the CPU is currently processing, like instructions and variables.

Native -

What It Is: Native memory is memory that is allocated outside the JVM's managed heap. It is
typically used by native code (e.g., JNI – Java Native Interface) and certain libraries like
DirectByteBuffer.
fi
fi
fl
Some operations require interaction with the operating system or native libraries, such as le I/O,
graphics processing, scanner , or networking. These operations often use native memory,
bypassing the garbage-collected heap.

JDK -

Development - provide runtime env to code / Project .

JIT compiler - Compilation: When a piece of code is executed multiple times, the JIT compiler
compiles that bytecode into native machine code for the speci c CPU architecture. Native code
is much faster to execute than interpreted bytecode.

JVM Architecture -

==

Permanent Generation (PermGen) - After java it has replaced with Metaspace

Metaspce - it is memory area , It is replacement of PermGem memory from java 8

Beni t - Dynamic Sizing , Native Memory: , No More PermGen OutOfMemoryErrors , Reduced


Memory Leaks , GC Impairment ,

=====

Access speci ers de ne the visibility or scope of classes, methods, and variables in Java.
They determine whether other classes can access the elements of a class or not. The four main
access

Private -
Default -
Protected - Inheritance
Public.

=======

Access modi ers are a broader category that not only includes access speci ers but also
includes other modi ers that a ect how a member behaves in Java. The main access
modi ers

Public
Proceed
Default
Private
Final
Abstract
Static
Synchronised
Native
fi
fi
fi
fi
fi
fi
ff
fi
fi
fi
Transient - If you don’t want to write elds using serizlizable
Volatile

=======

Data Type

Primate - int , oat , boolean , double , char , byte , long , short

8 byte - Long , Double


4 byte - oat , int
2 byte - short , char
1 bit - boolean
1 byte - Byte

Non Private -

String , Array , Collection - 8 byte

================

What is Unicode ?

Universal International Standard character encoding

Max -\UFFFF
Min - \U0000

Internationalization: With the rise of global communication and the internet, there was a
growing need for a character encoding system that could accommodate multiple languages and
scripts. Prior to Unicode, many encoding systems were limited to speci c languages (like ASCII
for English), making it dif cult to represent text in other languages.

===================

Naming convention -

Class name - start with upper case


Interface - Starts with upper case
Method - starts with lowercase
Variable - starts with lowercase
Package - starts lowercase
Constants - UPPER case

=====================

Object - Is an instance or class wich has state and behvarious

State - Varaibles Behaviours. - method

===================
fl
fl
fi
fi
fi
Why we need mothods -
Code rreaulbality

=======================================

How many ways we can create java Object. S -

// New keyword
Executore objExe = new Executore();

// New instance
Class objClass = [Link]("[Link]");
Executore objclassin = (Executore) [Link]();

// Clone in java

Two types

Shall cloning - Reference copy - From main Object

public Object clone() throws CloneNotSupportedException


{
return [Link]();
}

Deep cloning -

// factory method
// Decerilizarion

========

Constructor - Public , protected , private .


Class can be- Public , protected , default , nal ,Scriptfp

Special method to initialise Object


Two

Default - No Argument , Default


No arg - you have declared constuore
Default - we did not

Parmaetersize - pass the different values

Rules -
fi
- Same name as class
- We can’t add return type
==================

Static

Main - Memory management .

Variable - static variable


Method -
Block -

Static nal variables can be instqailized only in static block

Can we delayer local variable as static - no

===============================

Java principle
SOLID -

S - Single Responsibility
O - Open for extension and close for modi cation (Base calss should not be modi ed )
L - Liskov Substitution Principle (LSP) - The Liskov Substitution Principle says a subclass
should be substitutable for its superclass without altering the correctness of the
program.

This means that when you design a subclass, it should behave in a way that
doesn’t violate the expectations set by the superclass. If a class B is a subclass
of A, you should be able to replace instances of A with instances of B without
breaking the program.
I - Interface Segregation Principle - No client should be forced to depend on methods
it does not use.
D - Dependency Inversion Principle (DIP).

High-level modules should not depend on low-level modules. Both should depend on
abstractions. Abstractions should not depend on details. Details should depend on abstractions.

===
Inheritance -

Single , Multiple , Multilevel , heriricahkley and hybrid


fi
fi
fi
Why - Avoid code duplication , Method Overriding , Extends keyword compulersry

====
Abstraction

===
Encapsulation

- wrapping the data members in single method


- Make read and write only class
Java bean - fully enscapluated

Rules - data members to be private


- Serilizaed

=====

Interface

Marker Interface: An interface with no methods. It is used to mark a class with some metadata.
For example, Serializable, Cloneable and remoting in Java.
- Serialisation - ObjectOutputStream - writeObject() , ush() , close()
- Deserilization - ObjectInputStream - readObject()

Its different topic - Externalisation - Write Object in to byte stream in compressed format .

Externalization is a more advanced way of customizing the serialization process. It allows you
to control the serialization and deserialization of an object's state more explicitly than the default
serialization mechanism. You do this by implementing the Externalizable interface,
which requires you to de ne the writeExternal and readExternal methods

serialVersionUID what it is is used for version control - InvalidClassException to avoid the


exception

EX - private static nal long serialVersionUID = 1L;

Functional Interface: An interface with only one abstract method, introduced with Java 8 for
lambda expressions. For example, Runnable, Callable, and Comparator.
Normal Interface: These are standard interfaces that can have multiple abstract methods. For
example, List, Map, etc.

============

Polymorphism in java -
fi
fi
fl
Runtime - Overrding - Dynamic binding
Complitime - Overloading - Static binding

Overloading -

Same class ,
Same method name
Diffret parameter ,

Is there Operatorovrloading in java ?

No - But there operator which act like operator overloading that is + only

- Can I de ne one method as static and one non static - yes


- Can I have same method name and part only different with return type ? No
- Does not check the return type it doesn’t matter
- Can we declared overloaded method as nal Yes

Overrding -

Inheritance
Same name
Same param
Visibility of the method
Return type ? It should be the same .

Can we override private , Static , Final method - no


Default - yes withering package outside package we can not .

Can we change the return type no but there concept called Co -varient return type -

Covariant return type is a concept in Java that allows a subclass to override a method of its
superclass with a return type that is a subclass of the original return type. This means that when
you override a method, you can change the return type to a more speci c type (subclass) while
still maintaining the same method name and parameter list.

Key Points:

1. Same Method Signature: The method name and parameter list must be identical to the
method in the superclass.
2. Subclass Return Type: The return type of the overriding method can be a subclass of the
return type de ned in the superclass.
fi
fi
fi
fi
Parent Object class return. - then your subclass method can return Object , String , and
StringBuffer bus Object class is super class of String and StringBuffer
Parent Class method return Number then child class method can return - Integer , oat ,
double

Can we override static , private , nal no


If super class method is protected can we override the method as private no it is not
possible

PPDP — Private , Protected , Default public - (Left to right is possible )

You can not reduce the visibility

Ex if the super class method is default you can not change the visibility in sub class
method to Private or Protected .

You can increase the vislisblity but can not Decrease

======================================================

Instance initlizaltkion block

At the time of object creation .


In instance block u can use super and this keyword in static block you can not

====================

Final keyword - Apply restircuation

Method - Can’t not override ,


Class - Can’t not extends ,
Variable - Stop changing the value -
Blank nal variables where we can initialise it -
Decalarion time , Instance initlization block , Constructor

Static VS Final
Class leave. - Metod level
Static block - Decalarion time , Instance initlization block , Constructor
fi
fi
fl
What is static nal black variable ? - Should be initiate at a stick block or delcarion time

Can we declare constructor as nal - no


Can we make location variable as nal ? Yes
Can we make array nal in java - yes
Are static nal variables are thread safe ? Only primitive not derivred
=======================================================

Instance of Operator

- To determine the object is of speci ed class


-

Animal myDog = new Dog();


// Creating an instance of Dog Animal myCat = new Cat();
// Creating an instance of Cat
// Using instanceof to check the type of myDog
If (myDog instanceof Dog)
{ [Link]("myDog is an instance of Dog");
}

==============================

Java Array

- Collection of smiller type of obejct


Singel , Multi dimensional

Int a[ ] =new int[5];


a[0]=12;

Int a[] = {1,2,3};

Int a [ ] [ ] = new int [1] [2];

Disadvantaged - Fix size , Same Type

=================

Wrapeer classes -

Mechanimisam to convert object to primitive and primitive object

Class 8

Integer , Boolean , Charcter , Float , Double , Short , Byte , Long


fi
fi
fi
fi
fi
fi
valueOf , parseInt , toString , byteValue , intValue , doubleValue ,

Primitive to object ?

int i = 10;

Integer intVal = i;

Integer intValObj = [Link](i); // Autoboxing

// unboxing

int partint = [Link]();

What design pattern used by wrapper classes - Adaptor

Is the wrapper classes are immutable if yes why ? Yes

1. State Consistency

• Immutability ensures that once an object is created, its state cannot change. This
predictability is crucial in programming, as it allows developers to reason about the
behavior of their code without worrying about unintended side effects.
2. Avoiding Bugs

• When an object is immutable, it cannot be modi ed after creation, reducing the risk of
bugs that stem from modifying shared or referenced objects. This is particularly important
in multi-threaded applications where multiple threads might access the same object.
3. Thread Safety

• Immutable objects are inherently thread-safe because their state cannot change. This
means that multiple threads can operate on the same instance of a wrapper class without
the need for synchronization, simplifying concurrent programming.
4. Performance Optimization

• Java takes advantage of the immutability of wrapper classes to cache frequently used
values. For example, Integer caches instances for values between -128 and 127. If
you create an Integer with a value within this range, it will reuse the existing instance
instead of creating a new one, which saves memory and improves performance.
5. Simpler Design

• Immutability simpli es the design of classes and APIs. Users can safely share immutable
objects without worrying about changes affecting other parts of the code. This leads to
cleaner, more maintainable code.
6. Functional Programming Paradigms
fi
fi
• The immutability of wrapper classes aligns with functional programming principles,
which promote the use of immutable data structures to avoid side effects. This is
increasingly important as more Java developers adopt functional programming styles
introduced in Java 8 (like Streams and Lambdas).

After you reassign ii to 24, the original Integer object holding the value 10 still exists in
memory (due to caching) but is no longer referenced by ii.

Mutables wrapper classes as well in java

AtomicBoolean
AtomicInteger
AtomicLong
AtomicReference<V>
AtomicIntegerArray
AtomicLongArray
AtomicReferenceArray<E>

What is the different between - IMP

ValueOf() and ParseInt() -


Integer int
==============================

Recursion in java -

Method calling same method

===============

Does java is call by value or call by reference ? =

Java uses call by value while passing reference. .

Call by Value:

• In Java, when you pass a variable (either a primitive type or a reference) to a method, you
are passing a copy of its value.
• This means that any changes made to the parameter inside the method do not affect the
original variable outside the method.
Passing References:

• When you pass an object to a method, you are passing a copy of the reference (the address
in memory) to that object.
• This allows the method to modify the contents of the object (like its attributes), but if you
try to change what the reference points to (assign a new object), it won’t affect the
original reference outside the method.
======================

Strictfp. = Keyword in java

The strictfp keyword in Java is used to ensure that oating-point calculations yield
the same results on all platforms.

strictfp stands for strict oating-point. When you declare a class, method, or interface with
the strictfp modi er, you are enforcing the use of strict oating-point calculations, adhering
to the IEEE 754 standard.

Where can apply - Method , Class and interface

strictfp class StrictFPExample


{ oat calculate( oat a, oat b) { return a * b; // This operation will be strict } }

class Example { strictfp oat calculate( oat a, oat b) { return a * b; // Strict oating-point
operation } oat anotherCalculation( oat a, oat b) { return a + b; // Not strict, could yield
different results on different platforms } }


This we can not apply on - Variables , Abstract methods ,and Constructor

======================================

Inner classes in java -

Non Static
- Member inner class

Class A {
Class b{
}
}

Yes, an inner class (non-static member class) in Java can access all members of the outer class,
including private members. This is one of the key features of inner classes in Java.

you cannot have a static method in a non-static inner class (also known as a member inner
class) in Java.

In Java, the name of an inner class (both non-static inner classes and static nested classes)
depends on how it is nested within the outer class. The inner class's name is composed of the
outer class's name followed by the inner class's name, with a $ symbol used internally by the
Java compiler to separate them.
fl
fl
fl
fi
fl
fl
fl
fl
fl
fl
fl
fl
fl
fl
Ex = OuterClass$StaticNestedClass

- Anonymus Inner cLass

An anonymous inner class in Java is a type of inner class that doesn't have a name. It is often
used when you need to create a one-time, quick implementation of an interface, abstract class, or
concrete class, usually in a concise manner. Anonymous inner classes are typically used to handle
events or provide speci c behavior for a single-use scenario.

An anonymous inner class in Java is a type of inner class that doesn't have a name. It is often
used when you need to create a one-time, quick implementation of an interface, abstract class, or
concrete class, usually in a concise manner. Anonymous inner classes are typically used to handle
events or provide speci c behavior for a single-use scenario.

- Local Inner Class

A local inner class in Java is a class de ned within a block of code, such as a method,
constructor, or even within a loop or conditional block. It is local to the scope in which it is
de ned, meaning it can only be used within that block.

Static
- Static netset class

In Java, a static inner class (also known as a static nested class) is a class that is de ned inside
another class but is declared as static.

Cannot access non-static eld of the outer class

[Link] nestedInstance = new [Link]();


[Link]();

=================================

Packages in java -

Lang - Util - Awt

Default packages imported in java is Lang - [Link] , String Class - We dot need to
import anything
fi
fi
fi
fi
fi
fi
Can we import package twice same package ? Yes but no use .
Do you need to import subpackage ? Yes

What is Static Import ?

Static import in Java allows you to access static members ( elds and methods) of a class directly
without having to qualify them with the class name.

import static [Link];


import static [Link];

====================================

Design Patterns :

Creational - Creational design patterns deal with object creation mechanisms,

Structural - Structural design patterns deal with object composition, ensuring that if
one part of a system changes, the entire system doesn't need to do the same.

Behavioural - Behavioral design patterns focus on communication between objects,


what goes on between objects and how they operate together.

Creational : -

Singleton: Ensures a class has only one instance and provides a global point of access to it.

Rules :
- Private static data member / Object only one memory is created
- private constructor - No instance created
- public satic method so that we can access from anywhere without object creation ,.\

public class Singleton {


// Private static variable to hold the single instance. - Get memory only once
private static Singleton instance;

// Private constructor to prevent instantiation - Creating class instance


private Singleton() {}

// Public method to provide access to the instance. - You are allowing to access the created
instance
fi
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton(); // Create the instance if it doesn't exist
}
return instance;
}
}

Where we can use singletons -

Logging , Con guration Settings from File , Database Connection


Pooling,Cache,Thread Pool

Types SingleTone

Eagger loading - As soon as you load the calls that time it will create the
instance of the class
Lazy Loading - When you call the method that it will check if the instance ic
created if not then only create .

Question -

Can we write code in inside getInstance method ? - Yes


What is double checked locking in singleton ? - Check double
Is singleton calluses are thread safe ? No
How do we make single tone class as thread safe - Using synchronized
keyword

// Public static method to provide access to the instance


public static SingtoneEagger getInstance() {

if (objSingtoneEagger == null) {
synchronized ([Link]) {
if (objSingtoneEagger == null) {
objSingtoneEagger = new SingtoneEagger(); // Create the
instance if it doesn't exist
}
}

}
return objSingtoneEagger;
fi
}
Thread safe - Only one can access at a time - Concurrent modi cation
Exception
Non Thread Safe - This can not Does not throw

What is better to make the whole getinstace method as synchronised or only


the required block ?

It is better to make only the require dblock synchronised. So that other thread
can nish the work and wait for block and it will save the time for other and
execution will be after

Can we serialise singletons class ?

Yes we can
Can we deserialise it ? Yes we can but it will not return the singletons
instance .

a Singleton class can be serialized in Java, but care must be taken when deserializing the object.
By default, deserialization creates a new instance of the class

If you want to Decerlizes the singletons class but you want to get only one instance we need to
use readResolve() ;

// Method to resolve the instance during deserialization


protected Object readResolve()
{ return INSTANCE; // Return the existing instance
}

What are the disadvantages of singletons class

Unit Testing
Tightly coupled
If the singleton class is corrupt entire system will fail .

How many ways we can break singleton ?

- Serialisation
- Clone - Using closable inter implement the clone method in Singleton class then create then
use close method. -
Singleton singleton2 = (Singleton) [Link]();

- Re ection - Accessing the constructor of the ringtone class and set the constructor as
accessible true then create new Instance .
Constructor<Singleton> constructor = [Link]();
[Link](true);
// Make the constructor accessible
fl
fi
fi
Singleton singleton2 = [Link](); // Create a new instance

Exa :

package [Link];

public class SingtoneEagger {

// Private static variable to hold the single instance Eagger loading


private static SingtoneEagger objSingtoneEagger = new SingtoneEagger();

// Private static variable to hold the single instance Lazy loading


// private static SingtoneEagger objSingtoneEagger;

// Private constructor to prevent instantiation


private SingtoneEagger(){

// Public static method to provide access to the instance


public static SingtoneEagger getInstance() {

//Double checked Lockgng


if (objSingtoneEagger == null) {
synchronized ([Link]) {
if (objSingtoneEagger == null) {
objSingtoneEagger = new SingtoneEagger(); // Create the instance if it
doesn't exist
}
}

}
return objSingtoneEagger;

============================
Factory Method:

The Factory Design Pattern is a way to create objects without the client knowing the exact class
being created. Instead of the client directly making an object, it asks a factory to do it. The
factory decides which object to make and returns it.

The Factory Method Design Pattern is a creational design pattern in Java that
allows for the creation of objects without specifying their exact classes
- Client only know the factory method not how the Instace are created . He just know to use iit .
- The Factory pattern abstracts the creation logic, allowing easy extension and modi cation.
It decouples the client from speci c implementations, making the system exible and
maintainable.
- You can easily add new object types (e.g., new payment methods or noti cation channels)
without touching existing code, following the Open/Closed Principle.

Encapsulation of Object Creation Logic

• The Factory pattern encapsulates the logic of creating objects in one place. If the object
creation process changes, you only need to modify the factory rather than touching
multiple parts of your codebase. This makes your code easier to maintain and scale.
2. Promotes Loose Coupling

• It decouples the client code from the concrete implementations. The client interacts with
the factory to get objects instead of creating them directly, allowing you to change object
implementations without affecting the client code.
3. Improved Code Reusability

• Since the factory handles object creation, it can be reused across different parts of your
application. You can centralize complex object creation logic, making it easier to update
or extend the system in the future.
4. Enhanced Scalability

• The Factory pattern simpli es adding new classes or subclasses. If new types of objects
need to be created, you can easily extend the factory without modifying existing client
code, which is ideal for scalable systems.
5. Supports Dependency Injection

• It allows injecting different con gurations or dependencies at runtime. For instance, in a


live project where con gurations change based on environments (development, staging,
production), you can easily adapt by injecting appropriate objects via the factory.
6. Easier Testing and Mocking

• In unit tests, you can use the factory to inject mock objects or dependencies, which
improves testability. It isolates the creation process, making it easier to create controlled
test cases without dealing with complex setup code.
7. Encourages Adherence to SOLID Principles

• The Factory pattern aligns well with the Single Responsibility Principle (SRP) and the
Open/Closed Principle (OCP). The factory class handles the responsibility of object
creation, and new object types can be added without modifying existing code, which
follows OCP.
8. Improved Readability and Maintenance

• A well-structured Factory method makes the code more readable by clearly separating the
object creation process. This is useful in live projects with a large team, as it makes the
code easier to understand and maintain.
fi
fi
fi
fi
fl
fi
fi
============================================

-
Abstract Factory: Provides an interface for creating families of related or dependent objects
without specifying their concrete classes.

The Abstract Factory Design Pattern is a creational pattern that provides an interface to create
families of related or dependent objects without specifying their concrete classes. Unlike the
Factory pattern, which deals with creating a single product, the Abstract Factory pattern is used to
create families of related products. Each "factory" created by the Abstract Factory produces
related objects that follow a consistent theme or set of rules.

====================================
Prototype: Creates new objects by copying an existing object, known as the prototype.

The Prototype Design Pattern is a creational design pattern that allows you to create new
objects by copying an existing object, known as a prototype. This pattern is particularly useful
when the cost of creating a new instance of an object is more expensive than copying an existing
one.

Key Concepts

1. Prototype: The original object that serves as the template for creating new objects.
2. Cloning: The process of creating a copy of the prototype.
3. Deep Copy vs. Shallow Copy: A deep copy creates a new instance of the object and also
copies all objects referenced by the original object, while a shallow copy copies only the
references.

Bene ts of the Prototype Pattern

• Performance Improvement: Reduces the overhead of creating new objects when the
existing object is complex or expensive to create.
• Flexibility: You can create variations of an object without modifying the original
prototype.
• Decoupling: Clients can create objects without knowing the speci c class of the objects
they create.
• Ex -
// Clone the original car Car clonedCar = (Car) [Link]();

========================================

Builder: Separates the construction of a complex object from its representation, allowing the
same construction process to create different representations.

The Builder Design Pattern is a creational design pattern that provides a way to construct
complex objects step by step. It allows you to create different representations of an object using
the same construction process. This pattern is particularly useful when an object requires a large
number of parameters or when the construction process involves several steps that may vary.

Key Concepts
fi
fi
1. Builder: An interface or abstract class that de nes methods for creating parts of a
product.
2. Concrete Builder: A class that implements the builder interface and provides speci c
implementations for constructing the product.
3. Product: The complex object that is being built.
4. Director: A class that constructs the object using the builder interface. It de nes the order
in which to call the building methods.
Bene ts of the Builder Pattern

• Separation of Concerns: The construction logic is separated from the representation,


allowing for a clearer code structure.
• Flexibility and Readability: It improves the readability of the code by allowing you to
build objects step by step, making it clear what each step does.
• Immutable Objects: You can create immutable objects since the builder can construct the
object in a controlled way before returning it.
• Easier Object Creation: It simpli es the creation of complex objects that require
numerous parameters

=================================

DTO - Data Trader Object

Featur DT POJ JavaBea


e O O n
Purpos Transfer data across General-purpose Encapsulate data with
e processes object conventions
Business No business May contain business No business
Logic logic logic logic
Structur Flat Flexible Must follow
e structure structure conventions
Constructor May have multiple No Must have a default
s constructors restrictions constructor
Getters/ Optiona Optiona Required for
Setters l l properties
Serializatio Usually Not necessarily Often implements
n serialized serialized Serializable
Use Used in APIs or remote Used in general Java Used in frameworks (like
Case calls applications JSP)

====================================================
fi
fi
fi
fi
fi
Structural design pattern -

Adaptor Desing Pattern -


Scenario Explanation

• Client: Sends data in JSON format.


• System: Accepts data in XML format.
• Adapter: Converts JSON data to XML format so the system can process it seamlessly.

Bridge Design Patterns -

The Bridge Design Pattern is a structural design pattern that separates an abstraction from
its implementation so that the two can vary independently. It is often used when we need to
decouple complex hierarchies into separate hierarchies, allowing more exibility and reusability.

Bene ts of Using Bridge Pattern Here

1. Decouples Shape and Color:

◦ Shape and Color are independent, allowing you to extend them separately.
◦ Adding new shapes or colors does not require creating new subclasses for each
combination.
2. Avoids Class Explosion:

◦ Without the Bridge pattern, adding one more shape (e.g., Triangle) and one
more color (e.g., Green) would require 3×3 = 9 combinations.
◦ With the Bridge pattern, you can simply add one class for the new shape and one
for the new color.
3. Open/Closed Principle:

◦ New shapes or colors can be added without modifying existing code.

Composite design patterns :

The Composite Design Pattern is used to compose objects into tree structures to represent part-
whole hierarchies. It allows individual objects and compositions of objects to be treated
uniformly. Below are multiple examples in Java to illustrate the concept.

Proxy Design Pattern :

The Proxy pattern suggests that you create a new proxy class with
the same interface as an original service object. Then you update
your app so that it passes the proxy object to all of the original
object’s clients. Upon receiving a request from a client, the proxy
creates a real service object and delegates all the work to it.
fi
fl
The Proxy Design Pattern is a structural design pattern that provides an object representing
another object. The proxy acts as an intermediary, controlling access to the real object. The proxy
object can perform additional operations such as lazy initialization, access control, logging,
monitoring, or caching before delegating the call to the real object.

he Decorator Design Pattern is a structural pattern used to add additional responsibilities to an


object dynamically without altering its structure. It is often used to extend or enhance the
behavior of an object at runtime by wrapping it with another object.

In simple terms, a decorator is an object that allows you to add new behavior to an existing
object. Decorators are often used when you need to extend the functionality of classes in a
exible and reusable way.

Facade Design Pattern in Java

The Facade Design Pattern is a structural design pattern that provides a simpli ed interface to a
complex subsystem. It hides the complexity of the system and exposes only the necessary
operations. This is useful when you want to make a subsystem easier to use, while still
maintaining the system’s internal complexity.

Flyweight Design Pattern in Java

The Flyweight Design Pattern is a structural pattern that aims to reduce memory usage by
sharing common parts of objects instead of creating multiple instances of the same object. It is
particularly useful when many objects are created that share some common data but differ in
other aspects

=======

String

What is string -

Non primitive and Sequence of characters .


fl
fi
What string class implements. - [Link], Comparable<String>, CharSequence,
Constable, ConstantDesc

Why String is Immutable?

String immutability in Java provides several bene ts, including security, thread safety, memory
ef ciency, and consistent behavior in collections.

String Compare we use three way

==
Equals
compareTo

Concat the string =

Two ways

+
Contact();
// Internal implementation of + operator

String pp = (new StringBuilder()).append("Rahul").append("Rohan").toString();

// Does trim remove left or write space = Both

When intern() is called on a String object, the method:


• Checks if a string with the same content is already present in the String Pool.
• If the string exists in the pool, it returns the reference to that string.
• If the string does not exist in the pool, it adds the string to the pool and then returns the
reference.

public class StringInternExample { public static void main(String[] args) { // String literal stored
in String Pool String str1 = "Hello"; // New String object created in heap String str2 = new
String("Hello"); // Before interning [Link](str1 == str2); // Output: false (different
references) // Interning the string str2 = [Link](); // After interning [Link](str1 ==
str2); // Output: true (same reference from String Pool) } }

/////////////

StringBu er and StringBuilder // Mutables class

eatur Strin StringBuilde StringBuffe


e g r r
Defini Immutable sequence Mutable sequence of characters Mutable sequence of
tion of characters. (non-thread-safe). characters (thread-safe).
fi
ff
fi
Use Used when the string content Used for non-thread-safe Used for thread-safe
Case doesn’t change often. string modifications. string modifications.

String StringBu er. StringBuilder

Immutable no. no

Concat use too less less


Much memory

Override Equals No No
And compareTo
Methods

Sysnchronised. Yes. No

Replace method use 3 param use 3 param


Use two

================

- How to create immutable class in java :


Final class and Pramater constructor and private nal datamemebrs and no setter .

- Making a parameterized constructor in an immutable class serves a critical purpose: it


allows initialization of the immutable object’s state at the time of creation. Since the state of an
immutable object cannot change after it's created, all its elds must be set during construction.

- How does toString() word internally ?

Executor ee = new Executor();


[Link]("To string method : "+[Link]());

op = [Link]@3abfe836

[Link]().getName()+”@"+[Link](hashCode())

— StringTokenizer it works like split() and it has been replaced by split

- Di erence between Sting , StringBu er and StrinBuilder


- String class replace method .
- Why string is immutable ?
- How to convert string to char and char to string ?

String chararr = "rahul";


char sschar = [Link](1);

String sscharcon = [Link]();

- How to convert string to byte


getByte()
ff
ff
ff
fi
fi
- Di erence between char and string ?
Char - mutable - change it
String - immutable - You can not
- Why char is preferred over the String ?
Char is mutale and string is not hence if we store the password in String it will be always
there .

-What is SCP or what Stringpool ? When you create string using Laiteral it stops the values in
String pool
-String is primitive or non primitive ?
-Which one is the nal calls in all other String , StringBu er and StringBuildr - All of them .
- can we cal String class methods using string literal ? Yes
- When you create a string using the new String("hello") syntax without using a
string literal anywhere, Java will create two objects in memory:
1. String in the Heap: The new String("hello") creates a new String object in
the Heap. This object contains the string "hello".

2. String in the String Pool: When you create a String using new
String("hello"), the string literal "hello" is implicitly added to the String
Pool (if it isn't already there) when it is used inside the new statement. So, even though
you didn't explicitly use the string literal "hello", the string value will be added to the
String Pool.

================================================

Object Class in java :

- it is mother of all classes

How many methods :

Clone()
equals()
toString()
getClass()
Notify()
notifyall()
wait()
hasHcode()
nalised() - it is always called by GC (Garbage Collection)

Imp methods - hashCode() and Equals ();

- Which class does override equal and hashcode method - StringBu er and StrinBuilder
- Why wait notify and notify al in object class - Because these methods only called on Object
and These methods are used for Object commutation .
- Any nal method in Object calss ? Wait , Notify and Notifall .
- What is hashCode ? What is HasshCode Contract ?

1 - If the two objects are equal using equal method . Then has code should return the same
integers .
2 - If the two objects are equal using equal methods does not guaranty it will return the same
has code .
3 - Whenever it is invoked on the same object more than once during an execution of java
application it should return the same has code .
fi
ff
fi
fi
ff
ff
What is hashCode ? -

No, the hashCode() method in Java does not return the memory location of the object. While
the default implementation of the hashCode() method in the Object class might return an
integer derived from the memory address in some JVM implementations, this is not guaranteed
and is generally considered an implementation detail.
What Does hashCode() Return?

• Return Type: It returns an integer (int) that is used to identify the object in hash-based
collections.

• Contents of the Hash Code: The integer returned by hashCode() is typically derived
from the object's state, but it does not directly re ect the memory location. Instead, it is a
computed value based on the object's elds or other factors that are used for comparison.

* When we overdid the Hascode and Equal methods ? To compare the object and thee values ?

* How to compare two objects using Hashode and Equal ?

* In below scerios we use hascode and equal method - VIMP

- To check if the different objects are same .

- This will help you in collection for removing duplicate object .

Code -

@Override
public int hashCode() {
return [Link](dep, empId, name);
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
Employee other = (Employee) obj;
return [Link](dep, [Link]) && empId == [Link] &&
[Link](name, [Link]);
}

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class EmployeeExecutor {


fi
fl
public static void main(String[] args) {
Employee emp = new Employee(100 ,"Mohini" , "IT");
Employee emp1 = new Employee(100 ,"Mohini" , "IT");

Employee emp3 = new Employee(200 ,"Jotiram" , "CX");

// Checking two object with same value

[Link]([Link](emp1));
[Link]([Link](emp3));

List<Employee> eeList = new ArrayList<>();

[Link](emp);
[Link](emp1);
[Link](emp3);

[Link](eeList);

List<Employee> eeList2 = new ArrayList<>();

[Link](emp1);

//Checking two list

[Link]([Link](eeList2));

Set<Employee> setEE = new HashSet<>();


[Link](emp);
[Link](emp1);
[Link](emp3);

[Link](setEE);

///////

}
}

true
false
[[Link]@89d52224,
[Link]@89d52224,
[Link]@eab7310]
false
[[Link]@89d52224,
[Link]@eab7310]

true
false
[[Link]@0,
[Link]@0,
[Link]@0]
false
[[Link]@0,
[Link]@0]

====

. What is the role of the hashCode() method in Java collections like


HashSet and HashMap?
Explanation:
The hashCode() method returns an integer that represents the object's hash value. Collections
like HashSet and HashMap use the hash code to quickly locate and compare objects. If two
objects are considered equal according to the equals() method, they must return the same
hash code.

In your Employee class, the hashCode() method uses the [Link]() function
to combine the hash values of the dep, empId, and name elds. This ensures that two
Employee objects with the same empId and name will have the same hash code, which is
crucial for proper operation in hash-based collections.

2. Why do we need to override both equals() and hashCode() when


using collections like HashSet or HashMap?

Explanation:

• Consistency: The general contract between equals() and hashCode() in Java is


that if two objects are equal according to the equals() method, they must have the
same hash code. This ensures consistency between the two methods and prevents issues
when objects are stored in hash-based collections like HashSet or HashMap.
In your code:
fi
◦ The equals() method checks if two Employee objects are logically equal
based on dep, empId, and name.
◦ The hashCode() method calculates the hash code based on the same elds,
ensuring that equal objects have the same hash code.
• HashSet: The HashSet uses the hash code to group objects into "buckets" for fast
lookup. If two objects are equal (according to equals()), they must have the same
hash code so that the HashSet can correctly nd the object in the right bucket.

• HashMap: Similarly, the HashMap uses the hash code to determine the "bucket" where
the object should be stored and retrieves it ef ciently based on the key.

3. What will happen if the hashCode() method is overridden, but the


equals() method is not?
Explanation:
If you override the hashCode() method but not the equals() method, the collection
might still store objects based on their hash codes, but comparisons might be incorrect.
Speci cally:

• Objects that should be considered equal (based on business logic, such as empId and
name) could be treated as different if their hash codes differ.
• Since HashSet and HashMap rely on both methods for equality checks and
placement, failing to override equals() could lead to incorrect behavior, such as
duplicate objects being stored in a HashSet.
For example, without equals(), the HashSet might allow two objects with the same
empId and name but different reference addresses, because the default equals() method
from Object compares object references (memory locations), not content.

4. What will happen if the equals() method is overridden but the


hashCode() method is not?
Explanation:
If you override equals() but do not override hashCode(), you may violate the hashCode
contract, which could lead to unexpected behavior in hash-based collections. Speci cally:

• If two objects are equal according to equals(), but they have different hash codes, the
collections like HashSet or HashMap may behave incorrectly.
• For instance, when you add an object to a HashSet, the hashCode() is used to
determine which "bucket" the object belongs to. If two equal objects have different hash
codes, the HashSet will fail to nd the matching object and might store duplicates.
5. Scenario: You have two Employee objects with identical empId and
name, but they belong to different departments. What will happen when you
add them to a HashSet?

Explanation:
In this case, two Employee objects have the same empId and name, but different dep.

• The equals() method compares all three elds: dep, empId, and name.
fi
fi
fi
fi
fi
fi
fi
• Since the dep eld differs between the two objects, the equals() method will return
false (they are not equal).
• Consequently, the hashCode() method will return different hash codes for the two
objects because dep is a part of the hash calculation.
• As a result, when you add both Employee objects to a HashSet, they will be treated
as distinct objects and both will be added to the HashSet.
Example Code for this Scenario:

java
Copy code
Employee emp1 = new Employee("IT", 101, "Alice");
Employee emp2 = new Employee("HR", 101, "Alice");

HashSet<Employee> employeeSet = new HashSet<>();


[Link](emp1);
[Link](emp2);

[Link](employeeSet); // Both emp1 and emp2 will


be added since they are not equal due to 'dep' difference.
6. Scenario: You have two Employee objects with the same empId, name,
and dep. What will happen when you add them to a HashSet?

Explanation:
If both Employee objects have the same empId, name, and dep, they are logically equal
according to the equals() method.

• The hashCode() method will also return the same hash code for both objects.
• When you add the second object to the HashSet, it will not be added, because the
HashSet already contains an object that is considered equal to the new one based on
equals(), and both objects share the same hash code.
Example Code for this Scenario:

java
Copy code
Employee emp1 = new Employee("IT", 101, "Alice");
Employee emp2 = new Employee("IT", 101, "Alice");

HashSet<Employee> employeeSet = new HashSet<>();


[Link](emp1);
[Link](emp2);

[Link](employeeSet); // Only one object (emp1


or emp2) will be in the set.
7. What would happen if the empId was not included in the hashCode()
and equals() methods?
fi
Explanation:
If empId was excluded from both hashCode() and equals() methods:

• Two Employee objects with the same empId but different name or dep would be
considered equal based on the equals() method (since empId is not involved in the
comparison).
• However, this would be logically incorrect because empId is a key identi er for
employees, and two employees with different name or dep but the same empId should
not be considered equal.
• Also, since empId is not included in hashCode(), it could result in collisions in
hash-based collections, causing inef cient lookups and possible errors.
8. Can you add objects with different empId but the same name and dep to
the same HashSet?

Explanation:
Yes, you can add objects with different empId values but the same name and dep to the same
HashSet, as long as the equals() and hashCode() methods are correctly implemented
to re ect the equality logic. If empId is included in both equals() and hashCode(), they
will be treated as different objects because empId is a part of their equality check.

=====================================

Exception handling

Throwable - Class

Exception class Error - class - Stack over ow error , Out of memory

Checked (Compile ) and unchecked (Run time )

Di erence Betweee

Exception - Can be handled


Error - You need to solve
ff
fl
fi
fl
fi
Imp keyword in java

Try , catch , nally ,throw , and throws .

Can we delayer only try without catch or nally ? - You can not
Can we have multiple catch block ? Yes at time only one catch block will be executed .
Will the nally block always executed ? Yes
Discussed why nally is IMP - close db connection , close les …..
Catch block should follow the most speci c to most generic sequence .
What is nested try block ?
Finally - use for IMP code . There few scenarios where nally block to be executed \
- [Link]();
- Hardwere failure

Finally block should always followed by try and catch .


For each try there can be one or more catch blocks but only one nally block .

What is throw keyword ?

Use tot throw the exception explicitly .

int age = 10;


try {
// check vote limit
if(age < 16) {
throw new Exception("Please come back once you grow up");
}
}
catch (ArithmeticException e) {

}
catch(Exception e) {
[Link](e);
}

Throw is always used with new keyword

Throws keyword -

Throws indicate looking at the logic there may be exception or not .

The throws keyword used to propagate / forward the exception from one method to another -

// Method A calls Method B


public void methodA() throws Exception {
[Link]("Inside methodA");
methodB(); // Propagates the exception to methodA
}

// Method B calls Method C


fi
fi
fi
fi
fi
fi
fi
fi
public void methodB() throws Exception {
[Link]("Inside methodB");
methodC(); // Propagates the exception to methodB
}

// Method C throws an exception


public void methodC() throws Exception {
[Link]("Inside methodC");
throw new Exception("Exception thrown from methodC");
}

Throws keyword used with method and class .


If you calling a method which is throwing excpleion using throws keyword you can re throw the
exception or you can handle the exception .

Di rent between throw and throws keyword

Throw Throws
Throw exclipctly exception Declare exception
Throw followed by instance - new Method and class
You can not throw the mutliple You can Throw multiple exception
Exception methodE() throws IOException , Exception {

What is the di erence between Final and Finally and Finalised ?

eatur fina finall finalize(


e l y )
Defi Keyword to define constants, Block for cleanup Method called by the garbage
nitio prevent inheritance, or method code in exception collector before object
n overriding. handling. deletion.
Contex Variables, methods, and Inside try-catch Part of the Object
t classes. blocks. class.
Purpos To impose To ensure resource To perform object
e restrictions. cleanup. cleanup.
Execu At compile-time (for variables/ Always executes after Automatically by the
tion methods/classes). try or catch. garbage collector.
Exa final int finally protected void
mpl x = 10; { [Link]("D finalize() { ... }
e one"); }

3. finalize() Method (Deprecated in Java 9, Removed in Java 18)

• Purpose: Used for cleanup operations before an object is garbage collected.


• Context: De ned in the Object class and can be overridden.
Key Features:

• It is called by the garbage collector before reclaiming the memory of an object.


ff
fi
ff
• Rarely used in modern Java because of better alternatives like try-with-
resources and manual cleanup.

What is try-with-resources?

The try-with-resources statement in Java is used to ensure that resources (like les,
streams, or database connections) are closed automatically after the operations on them are done.
It was introduced in Java 7.

A resource must implement the AutoCloseable interface (or its subinterface,


Closeable) for it to work with try-with-resources.

// Using try-with-resources to manage the FileReader and BufferedReader try (FileReader


leReader = new FileReader( lePath); BufferedReader bufferedReader = new
BufferedReader( leReader)) { String line; while ((line = [Link]()) != null)
{ [Link](line); } } catch (IOException e) { [Link]("An error occurred: " +
[Link]()); }

Explanation

1. Resources in try Statement:

◦ FileReader and BufferedReader are declared in the parentheses of the


try statement.
◦ These objects implement the AutoCloseable interface, so they will be
automatically closed after the try block is executed.
2. Automatic Resource Management:

◦ You don’t need to explicitly close the resources (e.g.,


[Link]()).
◦ Even if an exception occurs, the close() method of the resources will be called
automatically.

Custom Exception : -

Used to throw the User exception


You can create your own exception class
Need to extend the Exception Class -

How to create custom exception - Declare the calls , Extend the exception class .

Is there any method in Exception class ? No it has only constructors -

Es - Exception() , Exception(parm , parm) , Exception(parm, parm , parm )

All the methods are coming from Throwable class . -


fi
fi
fi
fi
printTrackTrace()
toString() - coming from object class
getCause()
getMessge()
getSuppressed()

Metho Descriptio Example Use


d n Case
printStackTra Prints the stack trace to the console Debugging to locate the source of
ce() or a log. an error.
toStri Returns a string representation of the throwable Logging or quick inspection
ng() (class name + message). of exceptions.
getCause( Retrieves the root cause of the For analyzing chained
) exception. exceptions.
getMessage( Retrieves the detailed message of the For user-friendly error
) exception. messages.
getSuppres Retrieves suppressed exceptions (e.g., in try- For handling multiple
sed() with-resources). exceptions together.

How to create custom exception

- Create a class
- Extends Exception class .
-

Earlier
Exception in thread "main" [Link]:
Come back later
at
[Link]([Link])

After customs exception Extends Exception class

Exception in thread "main"


[Link]: Come back
later
at
[Link]([Link])

Ex -

package [Link];

public class VotingAgeLimitException extends Exception {


VotingAgeLimitException(String excep){
super(excep);
}

Call -

if(age < 16) {


throw new VotingAgeLimitException("Come back later");
}

Interview question -

What is exception ?
How exception can be handled ?
What is the di erence between Exception and Error
Can we keep other statements between tray and catch block ? No
Can we write try block without catch and nally ? No
What is unreachable catch block exception ? Most speci c to most generic ow missed it .

Ex - catch (Exception e) {
[Link]("Caught exception in main: " + [Link]());
}
catch (IOException e) {
[Link]("Caught exception in main: " + [Link]());
}

Hierarchy of the exception classes ?


What are the checked exception ?
What is the di erence between ClassNotFoundException and NoClassDefFoundError -

yp Checked Exception (subclass of Error (subclass of


e Exception) Error)
Ca Thrown when the application tries to dynamically Thrown when the JVM or a
us load a class using [Link](), classloader tries to load a class
e [Link](), or similar during runtime but the class is
missing or has failed to initialize.
When Happens at runtime when the Happens at runtime when a class was present
it requested class is not available in the during compile time but is unavailable during
occurs
Recoverclasspath. runtime.
Yes, as it is a checked exception and can No, as it is an error and indicates a serious
able? be handled in the code. issue with the application.
Examples The .class file is not in the The .class file was available during
of Causes classpath or the class name is compile time but has been removed or
misspelled. corrupted.
Can we keep any statement after nally block ? Yes
Can we throw the exception manually ?
Use of throw and throws keyword ?
How do you create cusomte exception
What is stack over ow ? - when stack memory is full .
ff
ff
fl
fi
fi
fi
fl
Which is calls is super class of all the exception class - ? Throable

What is printTrackTrace() ?
Can we write return statement in try catch block ? Yes but we need to add in try and catch both .

try {
return 0;
}
catch (Exception e) {
return 0;
}

Return statement in Try only or catch only will throw the error .
We can not write anything after return statement - Will get Unreachable code exception .

Ex -

try {
return 0;
[Link](); - Error line
}
catch (Exception e) {
return 0;
}

Can we write return statement in nally ? Yes

From java 7 we can catch multiple in catch block Ex -

If the superclass does not declare any exception:


• The subclass can declare checked exceptions but cannot declare unchecked exceptions.
If the superclass declares an exception:
• The subclass can declare the same exception or a subclass of that exception.
• The subclass cannot declare a parent or unrelated exception (e.g., declaring a broader
exception than the superclass).

==============

Garbage collection in java -

Java Garbage Collection


In java, garbage means unreferenced objects.
fi
Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.

To do so, we were using free() function in C language and delete() in


C++. But, in java it is performed automatically. So, java provides better
memory management.

Advantage of Garbage Collection


• It makes java memory ef cient because garbage collector
removes the unreferenced objects from heap memory.
• It is automatically done by the garbage collector(a part of
JVM) so we don't need to make extra efforts.

How can an object be unreferenced?

• By nulling the reference : A obj = null;


• By assigning a reference to another A obj = obnull;
• By anonymous object etc. Interface and Absaction .

- Is automatic process looking at heap a check used and unused


object and delete unused once .
- A obj = new A(); obj = it will store in obj stack . A object heap .
- Who controls the GC - JVM

But still you can request JVM to run GC - how ? Two ways

[Link]();
[Link]().gc();

- There is no guaranty GC will work and remove the unused memory .

What GC it is Dameon thread and Low priority thread


How many times does GC calls the nalised () - only once.
fi
fi
Young Generation GCs: Refer to GCs targeting pools like Eden Space or Survivor
Space.
Old Generation GCs: Refer to GCs targeting pools like Old Space.

What is the alto used by GC - Mark-and-Sweep


When does object is eligible for GC ? When object is not referred by active thread .
How can you request to run the nalise to execute -

[Link]().runFinalization();

GC always run on which memory - Heap

Heap

- To store object and there associated value


- shared amount all the thread and created atet start of application
- Heap memory is divided in two part
Eden Space:
• When an object is created, it is placed in the Eden space.
• If the Eden space lls up, a minor GC is triggered, and objects that are still in use are
moved to one of the Survivor spaces (S0 or S1).

Survivor Spaces:

• After surviving a GC cycle, objects are moved between S0 and S1.


• Once an object has survived a certain number of cycles (determined by the JVM's
MaxTenuringThreshold ), it is promoted to the Old Generation.

Objects in Eden are not promoted directly to the Old Generation unless special circumstances
arise (e.g., large objects with size exceeding a threshold).
Objects must rst be moved to a Survivor space and then survive the required number of Minor
GCs.
Once promoted, the object resides in the Old Generation, where Major GC is responsible for
reclaiming memory.

threshold - 8 you can set this as well - -XX:MaxTenuringThreshold=<value>

Stack
A obj = new A();
- To store the object reference ex - obj; methods calls , local variables , Addresss

Native

Register

Class

========
fi
fi
fi
Thread ?

What is multithreading in java

What is multiprocess and multithreading ?

Thread lifecycle ?

How to create thread ?


Two ways -

Extending thred class and Implement Runnable interface .

Runnable -
public class ThreadRblImpl implements Runnable {

@Override
public void run() {
[Link]("Thread is running");

public static void main(String[] args) {


// Create an instance of the Runnable
ThreadRblImpl myRunnable = new ThreadRblImpl();

// Pass the Runnable to a new Thread


Thread thread = new Thread(myRunnable);

// Start the thread


[Link](); // This will invoke the run() method in the Runnable
}

Thread class

package [Link];

public class ThreadExecutor extends Thread {

@Override
public void run() {
[Link]("Thread is running");
}

public static void main(String[] args) {


// Create a new instance of MyThread
ThreadExecutor myThread = new ThreadExecutor();
// Start the thread
[Link](); // This will invoke the run() method
}

Thread calls internally implements runnable interface


Runnable interface has only one method which is Run();
Thread class any methods : -

When to use Runnable interface and Thread class

Runable -

- Implement multiple interface as Runnable is interface


- When you want to separate the task (logic) from the thread itself.
When you want to share the same task across multiple threads.
When you don't need to subclass the Thread class.

Thread class -
When you want to create a custom thread.
When you need to override the thread's behavior (e.g., adding extra functionality like
setting priorities, etc.).
When you need to control the thread more directly by extending the Thread class.

Comparison of Runnable vs Thread


Aspect Runnable Thread
Can be implemented alongside Can't be used if your class already extends
Inheritance
other classes another class
Task Tasks can be reused across Each thread is specific to the class
Reusability different threads
Customization Limited to implementing run() Full control (can override other Thread
methods)
Thread Uses Thread for actual thread Directly manages its own thread
Management creation

When to Use Each in Different Scenarios:

1. Scenario 1: Simple Task Execution

◦ If you're only looking to execute a task in a separate thread, and you don't need to
extend the Thread class, use Runnable.
◦ Example: Running a simple background task in a multi-threaded environment.
2. Scenario 2: Need for Custom Thread Behavior

◦ If you need more control over the thread itself (such as adjusting its priority,
handling interruptions, etc.), extend the Thread class.
◦ Example: Creating a thread that does something speci c, like interacting with
system resources or changing thread priorities.
3. Scenario 3: Task Reusability and Thread Pooling

◦ If you need to create a thread pool, where tasks are executed by different threads,
use Runnable with a ThreadPoolExecutor.
◦ Example: Implementing a task executor that processes a large number of tasks
concurrently.

Thread class method -

start()
This method is used to begin the execution of the thread. It invokes the run() method
internally and starts the thread in a new, separate path of execution.

run()
This method contains the code that constitutes the thread’s task. The run() method is invoked
automatically when the thread starts, typically after start() is called.

sleep(long millis)
This method makes the current thread sleep (pause execution) for the speci ed number of
milliseconds.

Ex - [Link](2000);
fi
fi
join()

This method allows one thread to wait for the completion of another thread. It blocks the calling
thread until the thread it's called on nishes execution.

interrupt()
This method interrupts a thread, causing it to throw an InterruptedException if it’s
blocked in an operation like sleep() or wait(). It doesn’t stop the thread immediately but
signals it to stop.
Ex -
InterruptExample t = new InterruptExample(); [Link](); [Link](2000); // Main thread sleeps
for 2 seconds [Link](); // Interrupt the sleeping thread

isAlive()

This method checks whether the thread is alive or not. It returns true if the thread has been
started and has not yet nished.

getId()
This method returns the unique identi er assigned to the thread when it is created.

setPriority(int priority)
This method sets the priority of the thread. Valid priorities are integers between
Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10), with
Thread.NORM_PRIORITY (5) as the default.

Three type -
MIN -1
NORM. -5
MAX - 10

Ex -
PriorityExample t = new PriorityExample();
[Link](Thread.MAX_PRIORITY);
// Set thread to maximum priority [Link]();

getName()
This method returns the name of the thread. Every thread has a name, which can be set explicitly
or defaults to a system-generated name.

setName(String name)
This method allows you to set the name of the thread.
SetNameExample t = new SetNameExample();
[Link]("MyCustomThread");
[Link]();

yield()
This method causes the currently executing thread to pause and allow other threads of the same
priority to execute. It doesn't guarantee that the thread will immediately yield; it merely hints to
the thread scheduler.
fi
fi
fi
Ex - [Link]();

Running to runable state

currentThread()
This static method returns a reference to the currently executing thread.
Thread t = [Link](); // Get the current thread [Link]("Current Thread:
" + [Link]());

activeCount()
This static method returns the approximate number of active threads in the current thread's thread
group.

[Link]("Active threads: " + [Link]());

setDaemon(boolean on)
This method marks a thread as a daemon thread. A daemon thread is a low-priority thread that
runs in the background. The JVM terminates when all non-daemon threads are nished, and
daemon threads are killed automatically.
Ex -
DaemonExample t = new DaemonExample();
[Link](true);
// Set thread as daemon [Link]();

Suspend , Stop and Resume methods are removed from java 9 as those were causing rescue loss
and deadlock

What is a Thread Scheduler?

The Thread Scheduler in Java is a part of the JVM responsible for determining which thread
should run at any given time when there are multiple threads in the Runnable state. The
scheduler uses the operating system's thread scheduling mechanism to allocate CPU time to
threads.

Threads do not run simultaneously on a single-core CPU; they share CPU time. The thread
scheduler decides the order and amount of time threads get for execution.

• Java threads have priorities (Thread.MIN_PRIORITY to


Thread.MAX_PRIORITY), which can in uence the scheduling decision.
• Scheduling is platform-dependent and non-deterministic in Java.

Types of Thread Scheduling:

1. Preemptive Scheduling
In preemptive scheduling, the thread scheduler gives higher priority threads precedence over
lower-priority threads. If a higher-priority thread becomes runnable, it preempts (interrupts) the
execution of a lower-priority thread, even if the lower-priority thread is currently running.
fl
fi
Types of Preemptive Scheduling

1. Priority-Based Preemptive Scheduling.


2. Round-Robin with Preemption
3. Shortest Remaining Time First (SRTF)
4. Multilevel Queue Scheduling
5. Multilevel Feedback Queue Scheduling

Key Differences Between Types of Preemptive Scheduling

Priority Round- Multilevel Multilevel Feedback


Type SRTF
-Based Robin Queue Queue
Thread Shortest remaining Separate queues Dynamic queue
Focus Fairness
priority execution time for priorities adjustments
Not Not fair for long Limited to queue Ensured through
Fairness Ensured
guarante tasks priorities dynamic movement
Starvati ed
High Low High High Low
on Risk
Use Real- Time- Mixed Complex and
Batch processing
Case time sharing workloads adaptive systems
tasks systems

6. Time Slicing - Kind of default


In time slicing, the thread scheduler allocates a xed time slice (or quantum) to each thread in the
runnable state. After the time slice expires, the thread is paused, and another thread gets its turn,
regardless of priority.

Cann we start a thread twice ? - no You will get runtime error


Can we call directly run method instead of start? Yes but it will go in to the main() memory
Instead of thread .

ThreadPool -

What is a Thread Pool in Java?

A Thread Pool in Java is a collection of reusable threads that can be used to execute tasks.
Instead of creating a new thread for every task, the thread pool manages a set of worker threads
that are reused for multiple tasks. This improves application performance by:

• Reducing the overhead of thread creation and destruction.


• Limiting the number of active threads to prevent resource exhaustion.
• Providing ef cient task management.

How to Create a Thread Pool?

The Executors class provides factory methods to create thread pools. Below are the common
types of thread pools:

1. Fixed Thread Pool


A pool with a xed number of threads.
fi
fi
fi
If all threads are busy, new tasks are queued until a thread becomes available.

Executors - Class
ExecutorService - Interface which has Execute method
Ex - ExecutorService executor = [Link](3); // Pool with 3
for (int i = 1; i <= 5; i++) { int taskId = i; [Link](() -> { [Link]("Task " +
taskId + " is executed by " + [Link]().getName()); }); }

2. Cached Thread Pool


A pool with dynamically growing threads.
Threads are created as needed and reused if available.
Suitable for short-lived tasks.

ExecutorService executor = [Link](); for (int i = 1; i <= 5; i++) { int


taskId = i; [Link](() -> { [Link]("Task " + taskId + " is executed by " +
[Link]().getName()); }); }

3. Single Thread Executor


A pool with a single thread.
Tasks are executed sequentially in the order they are submitted.

ExecutorService executor = [Link](); for (int i = 1; i <= 5; i++)


{ int taskId = i; [Link](() -> { [Link]("Task " + taskId + " is executed by "
+ [Link]().getName()); }); }

4. Scheduled Thread Pool

A pool used for scheduling tasks at xed rates or delays.


ScheduledExecutorService scheduler = [Link](2); // Schedule a
task to run after a delay [Link](() -> { [Link]("Task executed after 3
seconds"); }, 3, [Link]); // Schedule a task to run at xed intervals
[Link](() -> { [Link]("Task executed periodically"); }, 1, 2,
[Link]); // Shutdown after some delay to observe scheduled tasks
[Link](() -> [Link](), 10, [Link]);

What is a ThreadGroup in Java?

A ThreadGroup in Java is a mechanism for grouping multiple threads into a single unit. It
allows threads to be organized hierarchically and provides a way to perform operations on a
group of threads collectively, such as setting their priority, interrupting all threads in the group, or
monitoring their status.

Thread groups were introduced in Java to simplify thread management, especially when working
with multiple threads. However, they are now considered somewhat outdated and are rarely used
in modern Java applications due to the introduction of the [Link]
package, which provides more robust thread management tools.

ThreadGroup is the class

ThreadGroup group = new ThreadGroup("MyThreadGroup");


fi
fi
Thread t1 = new Thread(group, () -> {

[Link]([Link]().getName() + " is running");

}, "Thread-1");

Thread t2 = new Thread(group, () -> {

[Link]([Link]().getName() + " is running");

}, "Thread-2");

[Link]();

[Link]();

[Link]("Thread Group Name: " + [Link]());

[Link]();

Metho Descriptio
d n
String Returns the name of the thread
getName() group.
ThreadGroup Returns the parent of the thread
getParent() group.
int Returns the number of active threads in the thread
activeCount() group.
int Returns the number of active thread groups in the thread
activeGroupCount() group.
void Prints information about the thread group to the standard
list() output.
boolean Checks if the thread group is a daemon
isDaemon() group.
void setDaemon(boolean Marks the thread group as a daemon
daemon) group.
void Interrupts all threads in the thread
interrupt() group.
void Destroys the thread group and removes it from its parent
destroy() group.
void Called by the JVM when a thread in the group
uncaughtException(Thread terminates due to an uncaught exception.
t, Throwable e)
What is shutdown hook in thread ?

What is a Shutdown Hook in Java?

A Shutdown Hook is a special construct in Java that allows you to de ne actions that should be
executed when the Java Virtual Machine (JVM) shuts down. This can happen due to:

1. Program termination (e.g., normal [Link]() call).


2. User interruption (e.g., pressing Ctrl + C).
3. System shutdown.
4. Killing the JVM process externally.

Runtime = is a class which has addShutdownHook()

Runtime runtime = [Link](); // Adding a shutdown hook


[Link](new Thread(() -> { [Link]("Shutdown hook executed:
Cleaning up resources..."); }));

ShutdownHook can be stopped using halt()

Interview Question -

What is thread ?
How to create thread ?
Difference between runnable and Thread class - Runnable has only one method run ..
How can you make sure threads starts from main and end with the same order ? Using join
method
What is be t of using volatile keyword ?

What is the volatile Keyword in Java?

The volatile keyword in Java is used to indicate that a variable's value will be modi ed by
multiple threads. Declaring a variable as volatile ensures:

1. Visibility: Changes made to a volatile variable by one thread are immediately


visible to other threads.
2. No Caching: The variable is always read from and written to the main memory (RAM)
rather than being cached in the CPU's register or thread-local memory.

Check mutable example ?

private static volatile boolean running = true;

Difference between synchronises and volatile ?


synchronises - can not use with variable and volatile can be.

What is the race condition in tow thread ? When two threads are trying to access the same
process / object
fi
fi
fi
How thread can communicate - using Wait , Notify and notify all methods .

What is a Deadlock in Java?

A deadlock in Java occurs when two or more threads are waiting for each other to release a
resource, resulting in a situation where none of the threads can proceed.

It typically happens when:

1. Multiple threads hold some shared resources (e.g., locks) and wait for resources held by
other threads.
2. A circular dependency of locks occurs, causing the threads to be stuck inde nitely.

Difference between wait and sleep method ? Wait - Release the lock and sleep don’t release the
lock .

Difference between yield and sleep - Yield - Running to runable to state and sleep - Running to
wait state .

What is object and class lock -


Using the synchronized Keyword

1. Object Lock:
• Used for instance synchronized methods/blocks.
• Lock is tied to the speci c instance of the class.
• Allows concurrent execution of instance methods for different objects.
• Synchronized instance methods or blocks use the object lock.
public synchronized void instanceMethod()
{ [Link]([Link]().getName() + " acquired object lock on instance
method"); try { [Link](2000); // Simulate some work } catch (InterruptedException e)
{ [Link](); } [Link]([Link]().getName() + " released object
lock"); }

2. Class Lock:
Used for static synchronized methods/blocks.
Lock is tied to the Class object of the class.
Only one thread can execute any static synchronized method in the class at a time.
Synchronized static methods or blocks use the class lock.

public static synchronized void staticMethod()


{ [Link]([Link]().getName() + " acquired class lock on static
method"); try { [Link](2000); // Simulate some work } catch (InterruptedException e)
{ [Link](); } [Link]([Link]().getName() + " released class
lock"); }

CountDownLatch and CyclicBarrier in Java

Both CountDownLatch and CyclicBarrier are synchronization aids in Java, part of


the [Link] package, that help coordinate the activities of multiple
fi
fi
threads. These classes are used to manage scenarios where threads need to wait for others before
they proceed or where threads need to be synchronized at speci c points.

1. CountDownLatch

A CountDownLatch is used to block one or more threads until a certain condition is met. It
allows one or more threads to wait until the latch reaches a count of zero. Once the count reaches
zero, all waiting threads are released.

• Constructor: CountDownLatch(int count)

◦ count is the number of times countDown() must be called before threads


can proceed.
• Methods:

◦ countDown(): Decreases the count of the latch by one.


◦ await(): Causes the current thread to wait until the latch's count reaches zero.
When to Use:

• When you want one or more threads to wait until a certain number of events (like tasks or
threads) are completed.

Ex -
int threadCount = 3;
CountDownLatch latch = new CountDownLatch(threadCount); // Count of threads to wait
for

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


new WorkerThread(latch).start();
}

[Link](); // Main thread waits until all threads nish their work
[Link]("All threads have nished. Main thread proceeding...");

2. CyclicBarrier

A CyclicBarrier is similar to CountDownLatch, but it is reusable. It is used to make a group


of threads wait for each other to reach a common barrier point before continuing execution. Once
the barrier is reached, all threads can proceed.

• Constructor: CyclicBarrier(int parties)

◦ parties speci es the number of threads that must reach the barrier before they
can proceed.
• Methods:

◦ await(): Causes the current thread to wait until all threads reach the barrier.
◦ reset(): Resets the barrier for reuse.

int threadCount = 3;
fi
fi
fi
fi
CyclicBarrier barrier = new CyclicBarrier(threadCount, () -> [Link]("All threads
reached the barrier. Proceeding..."));

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


new TaskThread(barrier).start();
}

// Let the threads perform their work and reach the barrier
[Link](3000);

Key Differences between CountDownLatch and CyclicBarrier

Feature CountDownLatch CyclicBarrier


Reusabili Not reusable. Once the count reaches zero, Reusable. Can be reset and reused.
ty it cannot be reset.
Use Case When one or more threads must wait for a When multiple threads must wait for
set of events to complete. each other at regular points.
Number CountDownLatch is used when waiting for CyclicBarrier is used to synchronize
of a specific number of threads to finish. threads at a common point repeatedly.
Threads Wait for tasks to complete before
Example All threads must reach a specific
Use Case proceeding. checkpoint before proceeding.

Key Differences Between Synchronization and CountDownLatch

Feature Synchronization CountDownLatch


Purpose Prevent thread interference on shared Coordinate and synchronize threads'
data. execution.
Ensures that only one thread can Wait for a specified number of threads or
Usage
access a critical section at a time. events to complete before continuing.
Type Mutual exclusion (locking). One-time synchronization (countdown
mechanism).
Applies to methods or blocks of code Applies to waiting for multiple threads to
Scope
to enforce mutual exclusion. complete a task.
Blocking A thread is blocked until it acquires A thread is blocked until the countdown
Behavior the lock. reaches zero.
Reusabili Reusable. Can be used as long as the Not reusable. Once the latch reaches zero, it
ty code requires synchronization. cannot be reset.
Example Ensuring data consistency (e.g., Waiting for all threads to finish a task before
Use Case incrementing a counter). proceeding.

==========================================================
ENUM

Enum is xed type data set or constraints .

- Type Safety . - Enums are type-safe, meaning you cannot assign any other value except the
prede ned constants to an enum variable.
- We can use this switch statement .
- Can be traversed . - You can traverse all enum constants using the values() method.
- Enum is a class .
- Enum can implements many interface but can not extends any class because it internally
extends Enum class .
- The java Enum elds are static nal by default .
- It is available from JDK - 1.5
- There is value method in enum class which return Enum class array .
- Java internally create Enum as nal class which extends the enum class .
- Enum class has private construture .
-The values() method is a compiler-generated method in Java enums, and it is not
explicitly declared in the [Link] class. Instead, the Java compiler adds it to every
enum during compilation.

Ways off creating ENUM -

enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,


SUNDAY; }

Enum class has methods - describeConstable


getDeclaringClass
ordinal
Interview Questions -

Can we caret instance of Enum class ? No because it has private constructor .


Can we have abstract methods in Enum class ? - Yes but need to provide implementation in the
enum class .
Can enum imlements any interface ? Yes
Can we override tostring method - yes .
What is Ordinal() Method in Enum ? It return the enum the way there declared as number 0 to n
Can we use enum with Treeset - Yes because Enum internally implements Comparable interface .
How to convert string to enum - using [Link]();

When to Use Enums

• When you have a xed set of constants.


• When you need type safety to avoid using arbitrary string or integer values.
• When you want to associate metadata (e.g., HTTP codes, descriptions) with constants.

==============================================================
fi
fi
fi
fi
fi
fi
Generic in java -

- Introduced from 1.5


- Used for Type safety
Example with Collection.
List<Employee> empList = new ArrayList<>();

Employee emp1 = new Employee(123 , "A" , "IT" , "Aylesbury");


Employee emp2 = new Employee(123 , "B" , "BP" , "Aylesbury");
Employee emp3 = new Employee(111 , "M" , "KP" , "Harrow");
Employee emp4 = new Employee(121 , "C" , "IT" , "Hayes");
Employee emp5 = new Employee(100 , "Z" , "Bp" , “Reading");

- Generic class -
// Generic class de nition
class Box<T> {
private T value;

// Constructor to set the value


public Box(T value) {
[Link] = value;
}

// Getter method
public T getValue() {
return value;
}

- Generic method -

class GenericMethodExample {

// Generic method that prints elements of any type


public static <T> void printArray(T[] array) {
for (T element : array) {
[Link](element);
}
}

public static void main(String[] args) {


Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"Java", "Python", "C++"};

[Link]("Integer Array:");
printArray(intArray); // Works for Integer array

[Link]("String Array:");
printArray(strArray); // Works for String array
}
}
fi
3. Generic Collection

// Create a List that stores String elements


List<String> fruits = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");

TEKVN

T stands for Type (generic placeholder).

// Generic class with placeholder 'T' class Box<T> { private T value; public Box(T value)
{ [Link] = value; } public T getValue() { return value; } public void setValue(T value)
{ [Link] = value; } }

E stands for Element (commonly used for collections).


E is often used as the placeholder for elements in collections such as List, Set, etc.
// List of elements (E represents the type of elements) List<String> fruits = new ArrayList<>();
[Link]("Apple"); [Link]("Banana"); [Link](“Mango");

K stands for Key (used in maps).


V stands for Value (used in maps).

K is the placeholder for key in a map, such as HashMap, TreeMap, etc. Maps store key-value
pairs.

// Map with Integer as Key (K) and String as Value (V) Map<Integer, String> map = new
HashMap<>(); [Link](1, "One"); [Link](2, "Two"); [Link](3, “Three");

N stands for Number (can be used when the type should extend a numeric type).

N is typically used as a placeholder when you want the generic to represent numeric types (like
Integer, Double, etc.). You can constrain N to types that extend Number (e.g.,
Integer, Float, Double).

// Creating a Map with Integer as Key and String as Value Map<Integer, String> map = new
HashMap<>(); // Adding key-value pairs to the Map [Link](1, "One"); [Link](2, "Two");
[Link](3, "Three");

What is wild card in generic. -


In Java, a wildcard in generics is a special character (?) used to represent an unknown type. It is
often used when you don't know the speci c type that will be used, or when you want to allow
multiple types but still maintain type safety. Wildcards help provide exibility when dealing with
generics.
fi
fl
There are three main types of wildcards:

1. Unbounded Wildcard (?)

• The unbounded wildcard (?) represents any type. This means you can use it in situations
where the type could be anything.

import [Link].*;

public class UnboundedWildcardExample {


public static void printList(List<?> list) {
for (Object obj : list) {
[Link](obj);
}
}

public static void main(String[] args) {


List<String> stringList = new ArrayList<>();
[Link]("Hello");
[Link]("World");

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


[Link](1);
[Link](2);

// Accepts any type of List


printList(stringList);
printList(intList);
}
}

2. Upper-Bounded Wildcard (? extends T)

• The upper-bounded wildcard (? extends T) allows you to specify that the unknown
type must be a subtype of T, including T itself.
• This is useful when you want to read from a structure and ensure that the objects are at
least of type T or a subtype of T.

import [Link].*;

public class UpperBoundedWildcardExample {


public static void printNumbers(List<? extends Number> list) {
for (Number num : list) {
[Link](num);
}
}
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
[Link](1);
[Link](2);

List<Double> doubleList = new ArrayList<>();


[Link](3.14);
[Link](2.71);

// Accepts any List of type Number or its subtypes


printNumbers(intList);
printNumbers(doubleList);
}
}

3. Lower-Bounded Wildcard (? super T)

• The lower-bounded wildcard (? super T) allows you to specify that the unknown
type must be a supertype of T, including T itself.
• This is useful when you want to write to a structure and ensure that you can safely add
elements of type T or its subtypes.

import [Link].*;

public class LowerBoundedWildcardExample {


public static void addNumbers(List<? super Integer> list) {
[Link](10); // Can safely add Integer or any supertype of Integer
[Link](20);
}

public static void main(String[] args) {


List<Number> numberList = new ArrayList<>();
List<Object> objectList = new ArrayList<>();

// Accepts any List of Integer or its supertypes


addNumbers(numberList);
addNumbers(objectList);

[Link](numberList);
[Link](objectList);
}
}

Interview Question -

- Generic type information is not available at runtime it is available at compile time .


- Advantages for Generic - No need of type casting .
- Write generic method that accept generic argument and return generic type ?
- Declare generic class - class Emp<T>

=======================================================

Collection

What is collection - Its framework which provide the mechanimisum to manupulate the group of
Objects .

What is hierarchy of Collection -


=======

List -

Methods from the List Interface

The List interface provides methods for list-speci c operations such as maintaining the order
of elements. These methods include:

Basic Operations

1. int size(): Returns the number of elements in the list.


2. boolean isEmpty(): Checks if the list is empty.
3. boolean contains(Object o): Checks if the list contains the speci ed
element.
4. Iterator<E> iterator(): Returns an iterator for the list.
5. Object[] toArray(): Converts the list to an array.
6. <T> T[] toArray(T[] a): Converts the list to an array of the speci ed runtime
type.
7. boolean add(E e): Appends the speci ed element to the end of the list.
8. boolean remove(Object o): Removes the rst occurrence of the speci ed
element.
fi
fi
fi
fi
fi
fi
9. boolean containsAll(Collection<?> c): Checks if the list contains all
elements of the speci ed collection.
[Link] addAll(Collection<? extends E> c): Appends all elements
of the speci ed collection to the list.
[Link] addAll(int index, Collection<? extends E> c):
Inserts all elements of the speci ed collection starting at the speci ed position.
[Link] removeAll(Collection<?> c): Removes all elements in the list
that are in the speci ed collection.
[Link] retainAll(Collection<?> c): Retains only elements that are in
the speci ed collection.
[Link] clear(): Removes all elements from the list.
Positional Access

15.E get(int index): Returns the element at the speci ed position.


16.E set(int index, E element): Replaces the element at the speci ed position
with the speci ed element.
[Link] add(int index, E element): Inserts the speci ed element at the
speci ed position.
18.E remove(int index): Removes the element at the speci ed position.
[Link] indexOf(Object o): Returns the index of the rst occurrence of the
speci ed element.
[Link] lastIndexOf(Object o): Returns the index of the last occurrence of the
speci ed element.
[Link]<E> listIterator(): Returns a list iterator over the elements
in the list.
[Link]<E> listIterator(int index): Returns a list iterator
starting from the speci ed position.
[Link]<E> subList(int fromIndex, int toIndex): Returns a view of
the list between the speci ed indices.

ArrayList -

Can contain Duplicate .


Maintain insertion order
Non Synchronised
Manipulation is very slow .
Null value is allowed.
Default size - 10 = 10 + (10 / 2) = 15. ( 50% increment .)
Arraylist internal use dynamic array .

Methods in ArrayList

The ArrayList class provides implementations of all the above methods from the List
interface and adds a few speci c methods, mostly related to capacity management:
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
1. void ensureCapacity(int minCapacity): Increases the capacity of the
ArrayList instance to ensure it can hold at least the speci ed number of elements.
2. void trimToSize(): Trims the capacity of the ArrayList to match its current
size, minimizing memory usage.

Ex -

ArrayList<String> listObj = new ArrayList<>();


[Link]("RAHUL");

Why Manipulation is very slow in ArrayList -

1 Shifting of Elements

• In an ArrayList, the elements are stored in contiguous memory locations.


• Insertion at a speci c index requires shifting all elements after that index one position to
the right to make space for the new element.
• Deletion at a speci c index requires shifting all elements after that index one position to
the left to ll the gap.
• This shifting operation has a time complexity of O(n) in the worst case, where n is the
number of elements being shifted.
2. Dynamic Resizing

• An ArrayList grows dynamically when it runs out of capacity. The default growth
strategy increases its size by 1.5 times the current capacity.
• During resizing, the entire array needs to be copied to a new memory location, which
takes O(n) time.
• Frequent resizing can slow down performance, especially when the initial capacity is
small, and a large number of elements are added.
3. Random Access is Fast, But Not Index-Based Manipulation

• While random access to elements using get(index) or set(index, value) is


O(1), manipulation (insertion or deletion) disrupts the order of elements, requiring
adjustments.
fi
fi
fi
fi
LinkedList =

Can contain duplicate .


Maintain insterion order .
Non synchronised
Manipulation is very is fast as shifting is not required .
Can allow null value .
The LinkedList does not use an internal array to store its elements, so it does not have a
xed or initial size.
Internally use Double linked list - Which has nodes

Single Linked ?
Doubled linked ?

Node-based storage: A LinkedList is made up of nodes, where each node contains data and
a reference to the next node. The LinkedList does not use an internal array to store its
elements, so it does not have a xed or initial size.
Dynamic growth: Each time you add an element to the LinkedList, a new node is created
and linked to the existing nodes. Since LinkedList uses nodes and pointers, it grows
dynamically as new nodes are added. There is no pre-allocated capacity, and it doesn't need
resizing like an ArrayList does.

Methods Unique to LinkedList


1. Add Elements:
◦ addFirst(E e) – Adds the speci ed element to the front of the list.
◦ addLast(E e) – Adds the speci ed element to the end of the list.
2. Access Elements:
◦ getFirst() – Retrieves the rst element of the list.
◦ getLast() – Retrieves the last element of the list.
◦ removeFirst() – Removes and returns the rst element of the list.
◦ removeLast() – Removes and returns the last element of the list.
◦ peekFirst() – Retrieves, but does not remove, the rst element of the list.
◦ peekLast() – Retrieves, but does not remove, the last element of the list.
3. Manipulation:
◦ removeFirstOccurrence(Object o) – Removes the rst occurrence
of the speci ed element from the list.
◦ removeLastOccurrence(Object o) – Removes the last occurrence of
the speci ed element from the list.
◦ push(E e) – Pushes the element onto the stack (adds the element to the front
of the list).
◦ pop() – Pops an element from the stack (removes and returns the rst element of
the list).
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Featur ArrayLis LinkedLis
e t t
Internal Dynamic Doubly linked
Structure array list
Access Fast Slow
Time (O(1)) (O(n))
Insertion/ Slow (O(n)) for middle; fast for Fast (O(1)) for beginning/
Deletion end middle
Memory Lower, but might waste space due to Higher, due to node
Usage resizing references
Thread Not Not
Safety synchronized synchronized
Resizin Expensive, requires resizing of No resizing, grows as nodes are
g array added
Best Use Frequent access, low insertion/ Frequent insertion/deletion, low
Case deletion access

Choosing Between ArrayList and LinkedList:

• If you need fast access by index and you're adding/removing elements mostly at the end
of the list, ArrayList is generally the better choice.
• If you need fast insertions and deletions at the beginning or middle of the list, and don't
require frequent random access, LinkedList is the better choice.

For Iteration we use multiple option :

Iterator -

ListIterator internally extends Iterator .

Iterator: Interface
• The Iterator interface provides basic methods to traverse a collection in one
direction, typically forward. The main methods are:
◦ hasNext(): Checks if there is a next element.
◦ next(): Returns the next element.
◦ remove(): Removes the current element (optional operation).
ListIterator: Interface
• The ListIterator interface extends Iterator and adds additional methods that
allow traversal in both directions (forward and backward) and more advanced operations
speci c to lists. These include:
◦ hasPrevious(): Checks if there is a previous element.
◦ previous(): Returns the previous element.
◦ add(E e): Adds an element to the list at the current position.
◦ set(E e): Replaces the last element returned by next() or previous()
with the speci ed element.
fi
fi
◦ nextIndex(): Returns the index of the element that would be returned by a
subsequent call to next().
◦ previousIndex(): Returns the index of the element that would be returned
by a subsequent call to previous().

For Each -

Vector -
Synchronised .
Legacy Class .
Increase size y 100% .
Default size is 10 .
Allow null .
Allow Duplicate .
Mention insertion order .
Vector internally uses an array

What is this - Vector<String> vvObj = new Vector(3,2);

Set the default size to 3 and increase by 2 .

For iterating Vector - We use Enumeration -

Enumeration is an Interface .

Enumeration<String> env = [Link]();


while([Link]()) {
[Link]([Link]());
}

Featur ArrayLis Vecto


e t r
Synchronizatio Not synchronized (not thread- Synchronized (thread-safe by
n safe). default).
Growth Grows by 50% of the current Grows by 100% (doubles its size) when
Factor size. full.
Default Default capacity is 10 Default capacity is 10
Capacity elements. elements.
Thread- Not thread-safe, so needs external synchronization if Thread-safe due to built-in
Safety used in multi-threaded environments. synchronization.
Perfor Faster in single-threaded applications due to Slower in single-threaded environments
mance lack of synchronization overhead. due to synchronization overhead.
Legacy Part of the Java Collections Framework A legacy class, part of the original
Status (introduced in Java 1.2). Java (pre-1.2).
Null Allows null Allows null
Elements elements. elements.
Duplicate Allows duplicate Allows duplicate
s elements. elements.
Insertion Maintains insertion Maintains insertion
Order order. order.

What is ConcurrentModi cationException - Multiple threads are modifying the same element .

How to avoid this ? Make it as synchronised .


How to make array As synchiormed -

Synchronised collection -
[Link](). Support add and remove opiste operation
[Link]()
[Link]()

Itertor is Fail fast - Throws Concurentmodi cation Exception


Enumeration is Falesafe - Does not throw .

STACK. -
Follows LIFO order
Thread-safe (synchronized)
Allows duplicate elements
Allows null values
Inherits from Vector, so it has dynamic resizing and a default size of 10
Provides methods like push(), pop(), peek(), empty(), and search()
Grow by 100 %
Yes, the Stack class in Java internally uses an array to store the elements.

Stack<String> stack = new Stack<>();

// Push elements onto the stack


[Link]("A");
[Link]("B");
[Link]("C");

// Peek at the top element


[Link]("Top element: " + [Link]()); // Outputs "C"

// Pop elements from the stack


[Link]("Popped element: " + [Link]()); // Outputs "C"
[Link]("Popped element: " + [Link]()); // Outputs "B"

// Check if the stack is empty


[Link]("Is stack empty? " + [Link]()); // Outputs false

// Search for an element


[Link]("Position of A: " + [Link]("A")); // Outputs 1 (1-based index)
fi
fi
==============================================================

Set -

Core Methods from the Set Interface


1. Basic Collection Operations:

◦ boolean add(E e)
Adds the speci ed element to the set if it is not already present.
◦ boolean remove(Object o)
Removes the speci ed element from the set, if it is present.
◦ boolean contains(Object o)
Returns true if the set contains the speci ed element.
◦ int size()
Returns the number of elements in the set.
◦ boolean isEmpty()
Returns true if the set contains no elements.
◦ void clear()
Removes all elements from the set.
◦ Iterator<E> iterator()
Returns an iterator over the elements in the set.
2. Bulk Operations:

◦ boolean addAll(Collection<? extends E> c)


Adds all elements from the speci ed collection to the set that are not already
present.
◦ boolean removeAll(Collection<?> c)
Removes all the elements in the set that are contained in the speci ed collection.
◦ boolean retainAll(Collection<?> c)
Retains only the elements in the set that are contained in the speci ed collection.
◦ boolean containsAll(Collection<?> c)
Returns true if the set contains all elements of the speci ed collection.
3. Stream and Parallel Stream Support:

◦ Stream<E> stream()
Returns a sequential Stream with the set as its source.
◦ Stream<E> parallelStream()
Returns a parallel Stream with the set as its source.

HashSet -

No duplicate
Unique values
No insertion order
Non Synchronised .
fi
fi
fi
fi
fi
fi
fi
One null value .
Default Size - 16 .
Internal using hashing mechanisms to store the value .
Only hash table-based storage

Why hashing came in to the picture ? - To save the memory..


How Does Hashing Work Internally?

Hashing is the process of converting data (keys) into a xed-size hash code that determines
where the data should be stored in a hash-based data structure like a HashMap or HashSet.
Here's how it works under the hood:

1. Key Components of Hashing

a. Key

The value that is used to identify an entry in the hash table (e.g., a string or number).

b. Hash Function

A function that computes an integer value (hash code) from the key. This hash code is then used
to calculate the storage index.

c. Hash Table

A xed-size array where elements are stored. The hash code determines the index in this array.

d. Collision Handling

When two keys generate the same hash code and index, a collision occurs. Techniques like
chaining or open addressing handle this.

Internal uses hashmap. -

HashSet<String> hashSet = new HashSet<>();

// Adding elements

[Link](“Apple”);

Apple is the Key not value

Internal working on add method in hashes -

public boolean add(E e) {


return [Link](e, PRESENT)==null;
fi
fi
}

int hash = [Link]();

hash = s[0] * 31^(n-1) + s[1] * 31^(n-2) + ... + s[n-1]

int index = hash % capacity; Size of the Bucket .

Index is the bucket location .

What if we get the same index for different value ?

Hash collision - How to solve has collision in java .

1. Chaining (Linked List or Other Data Structures)

Chaining is a method where each bucket in the hash table holds a collection of elements that have
the same hash code. This collection can be a linked list, a tree, or any other data structure.

How it works:

• If two or more keys hash to the same index, they are stored in a linked list at that index.
• When inserting a new element, it is added to the list at the calculated index.
• When searching, the list is traversed to nd the matching key.

2. Open Addressing (Probing)

In open addressing, if a collision occurs (i.e., a bucket is already occupied), the hash table
searches for the next available slot using a probing strategy. There are different types of probing
techniques:

• Linear Probing
• Quadratic Probing
• Double Hashing
Let's explore Linear Probing as an example.

Linear Probing

In linear probing, when a collision occurs, the next index is checked sequentially until an empty
slot is found.

Quadratic Probing: Instead of checking the next consecutive slot, quadratic probing checks
indexes with a quadratic formula (index + i^2), where i is the number of collisions. This
can help reduce clustering.
Double Hashing: A second hash function is used to calculate the next index if a collision occurs,
which reduces clustering even further.

Choosing the Right Collision Resolution Technique

• Chaining is generally better when there are lots of collisions because it doesn’t suffer
from clustering. However, it requires additional memory to store linked lists or other data
structures.
fi
• Open Addressing is more memory ef cient because it uses the space of the hash table
itself, but it can suffer from clustering, especially with poor hash functions or when the
table is too full.

LinkedHashset -

Allow one null ,

No Duplicate

Mention insertion order .

Default size 16

Non synchronised .

LinkedHashSet uses a hash table and a doubly-linked list

Propert HashSe LinkedHashSe


y t t
Backed Hash table Hash table + doubly-linked
by (HashMap) list
Insertion No order Maintains insertion
Order (unordered) order
Element Only hash table-based Hash table + doubly-linked list for
Storage storage order
Thread Not Not
Safety synchronized synchronized

load factor of 0.75 and increase by double .

TreeSet -

Set → SortedSet → NavigableSet → TreeSet:

No Duplicate

No null - not even single

Mention Assending order

Non synchronised .

No xed default size (the internal structure adjusts dynamically)


fi
fi
Internally used Red Black Tree .

TreeSet does not have a load factor like HashSet or LinkedHashSet because it does
not use a hash table for storing its elements

Featur HashSe TreeSe


e t t
Underlying Data Hash table Red-Black Tree (Self-balancing binary search
Structure (HashMap) tree)
Orderin No specific order Sorted order (natural ordering or custom
g (unordered) comparator)
Duplicate Does not allow Does not allow
s duplicates duplicates
Null Allows one null Does not allow null
Elements element elements
Time O(1) for add, remove, contains O(log n) for add, remove,
Complexity (average) contains
Ordering of No guarantee of Guarantees elements in ascending
Elements ordering order
Resizing (Load Uses a load factor (default 0.75) No load factor, resizing handled by Red-
Factor) for resizing Black Tree structure
Thread Not Not
Safety synchronized synchronized
Performance for Faster for basic operations (add, Slower for basic operations due to
Large Sets remove, contains) tree balancing
Use When order doesn't matter, fast lookups are When elements need to be stored in
Case needed sorted order
Null Allows one null Does not allow null
Handling element elements

What is Red black tree -

Its Self Blancing Tree .


Rules

Root node wil be alsyws Black ,

If tree is not empty then create leaf node with colour Red .

If Parent of new node is Back then exit .

If parent of new node is Red Then check the cooler of parent sibling .

Sibling is Black or new then do the suitable rotation

Sibling colour is read then recolour and also check if present of new node is not root node then
recolour and recheck .

No two adjacent red coded

Right node will be always bigger .

====================================================

Queue -

Featur LinkedLis ArrayDequ PriorityQueu


e t e e
Siz Dynamic (no fixed default Dynamic (default capacity: Dynamic (default capacity:
e size) 16) 11)
Synchronize N N N
d o o o
Duplicate Ye Ye Ye
s s s s
Allows Ye N N
null s o o
Internal Doubly Linked Resizable Binary
Structure List Array Heap
Ord Maintains insertion Maintains insertion Orders elements based on natural/
er order order comparator order
Performance O(1) O(1) O(log
(Add) (amortized) (amortized) n)
Performance O(1) (from O(1) (from O(log
(Remove) head) head) n)
Prefer When frequent insertions/ When frequent insertions/removals When ordering
red removals from both ends from both ends without null elements based on
Use priority
=============

MAP

Map - Is interface

Methods from Map -

void Removes all mappings from the


clear() map.
boolean Returns true if the map contains a mapping for the
containsKey(Object key) specified key.
boolean Returns true if the map maps one or more keys to
containsValue(Object the specified value.
value)
Set<[Link]<K,V>> Returns a Set view of the mappings contained in
entrySet() the map.
V Returns the value to which the specified key is mapped, or null if the map
get(Object contains no mapping for the key.
key)
boolean Returns true if the map contains no key-value
isEmpty() mappings.
Set<K> Returns a Set view of the keys contained in the
keySet() map.
V put(K key, V Associates the specified value with the specified key in the
value) map.
void putAll(Map<? extends K,? Copies all mappings from the specified
extends V> m) map to this map.
V remove(Object Removes the mapping for a key if it is present in the
key) map.
int Returns the number of key-value mappings in the
size() map.
Collection<V> Returns a Collection view of the values contained in the
values() map.

Default Methods (Java 8 and Later)

V Returns the value to which the specified key is mapped, or


getOrDefault(Object defaultValue if the map contains no mapping for the
key, key.
V defaultValue)Associates
V putIfAbsent(K the specified value with the specified key if the key is
key, V value) not already associated with a value.
boolean remove(Object Removes the entry for the specified key only if it is
key, Object value) currently mapped to the specified value.
boolean replace(K key, V Replaces the entry for the specified key only if it is
oldValue, V newValue) currently mapped to the specified value.
V replace(K key, Replaces the entry for the specified key with the specified value, if it
V value) is currently mapped to some value.
void forEach(BiConsumer<? super K,? Performs the given action for each
super V> action) entry in the map.
void replaceAll(BiFunction<? super Replaces each entry's value with the
K,? super V,? extends V> function) result of applying the specified
function.
V compute(K key, BiFunction<? super Computes a new mapping for the
K,? super V,? extends V> specified key using the given
remappingFunction) remapping function.
V computeIfAbsent(K key, Function<? Computes a mapping for the
super K,? extends V> mappingFunction) specified key if it is not already
present.
V computeIfPresent(K key, BiFunction<? Computes a new mapping for
super K,? super V,? extends V> the specified key if it is
remappingFunction) already present.
V merge(K key, V value, BiFunction<? Merges the specified value with
super V,? super V,? extends V> the existing value for the
remappingFunction) specified key.

Static Methods (Java 9 and Later)

static <K,V> Map<K,V> Returns an immutable empty


of() map.
static <K,V> Map<K,V> of(K k1, Returns an immutable map containing the
V v1, ...) specified mappings.
static <K,V> Map<K,V> Returns an immutable map containing
ofEntries([Link]<K,V>... the specified key-value pairs.
entries)
static <K,V> Returns an immutable key-value pair to be used in
[Link]<K,V> entry(K k, map creation with ofEntries.
V v)
static <K,V> Map<K,V> copyOf(Map<? Returns an immutable copy of
extends K,? extends V> map) the specified map.

HashMap -

- Key value pair

- One null key allowed and multiple null values

- Default capapctity 16

- Non Synchronised

- No duplicate key but duplicates values allowed but no use as it overrides latest Value .

- Load factor 0.75

- Does not mention any order

Internal Implementation of HashMap


1. Data Structure Used
◦ Array: The HashMap uses an array to store buckets. Each bucket represents a
storage location for key-value pairs.
◦ Linked List: Initially, if two or more keys map to the same bucket (collision), the
entries are stored in a linked list.
◦ Binary Search Tree (BST): When the number of entries in a bucket exceeds a
threshold (default is 8), the linked list is converted into a binary search tree
(balanced tree) for better performance.
-

How HashMap internally works -

It will have the bucket of size 16 .

Each index will have LinkedList

In the linked list each node will contain - Key , Value , Hash and Next which is below =

static class Node<K, V> implements [Link]<K, V> {


nal int hash; // Hash value of the key nal
K key; // The key
V value; // The value associated with the key
Node<K, V> next; // Pointer to the next node in the same bucket }

What is Key - Actual Key from the Put


Value - Actual value based on the Value .
Hash - calculated value from key using hashCode() .
fi
fi
Next - Added or next node . (Where the index is same for multiple Keys )

How does it nd the index - Inside Out method it has below logic

hash = [Link]();

Int index = hash & (n - 1);

N - size of bucket it mean capacity .

HashMapOwn methods -

compute(K key, BiFunction<? super K, ? Computes a new value for


super V, ? extends V> remappingFunction) the key using a function.
computeIfAbsent(K key, Function<? super Computes a value for the
K, ? extends V> mappingFunction) key if it's absent.
computeIfPresent(K key, BiFunction<? super Computes a new value if
K, ? super V, ? extends V> the key is already
remappingFunction) present.
merge(K key, V value, BiFunction<? super Merges the value with
V, ? super V, ? extends V> the existing value for the
remappingFunction) key.
forEach(BiConsumer<? super K, ? Performs the specified action for each
super V> action) key-value pair.
replaceAll(BiFunction<? super K, ? Replaces all values by applying the
super V, ? extends V> function) function to each key-value pair.

=========================================

LinkedHashMap
- Key value pair

- One null key allowed and multiple null values

- Default capapctity 16

- Non Synchronised

- No duplicate key but duplicates values allowed but no use as it overrides latest Value .

- Load factor 0.75

- One change Mention insertion order .

- Internally uses Doubled Linked List


fi
nternally, the node of the LinkedHashMap represents as the below:

▪ int hash
▪ K key
▪ V value
▪ Node next
▪ Node previous

Own Methods -

Metho Descriptio
d n
removeEldestEntry( Allows customization of eviction logic to remove the eldest
[Link]<K, V> entry when a certain condition is met (e.g., when the map
eldest) exceeds a certain size).
getAccess Refers to the constructor parameter that controls whether the
Order() LinkedHashMap should maintain the order of insertion or the order of
access (for LRU cache-like behavior).
==================

TreeMap

No Duplicate Key and and allow duplicate values .


Can’t not have null key but can have multiple null value .
Ascending order
Non Synchronised .
Internal used Red Black Tree
Default capacity no as it used redbalck tree

2. Navigational Methods (from NavigableMap and SortedMap interfaces):

• firstKey() – Returns the rst (lowest) key in the map.


• lastKey() – Returns the last (highest) key in the map.
• lowerKey(K key) – Returns the greatest key less than the speci ed key, or null if
there is no such key.
• floorKey(K key) – Returns the greatest key less than or equal to the speci ed key,
or null if there is no such key.
• ceilingKey(K key) – Returns the smallest key greater than or equal to the
speci ed key, or null if there is no such key.
• higherKey(K key) – Returns the smallest key greater than the speci ed key, or
null if there is no such key.
fi
fi
fi
fi
fi
• pollFirstEntry() – Removes and returns the rst (lowest) entry in the map.
• pollLastEntry() – Removes and returns the last (highest) entry in the map.
• subMap(K fromKey, K toKey) – Returns a view of the portion of the map
whose keys are between fromKey and toKey.
• headMap(K toKey) – Returns a view of the portion of the map with keys less than
toKey.
• tailMap(K fromKey) – Returns a view of the portion of the map with keys greater
than or equal to fromKey.
• navigableKeySet() – Returns a NavigableSet view of the keys contained in the
map.
• descendingMap() – Returns a view of the map in reverse order.

Comparator-Related Methods (from SortedMap interface):

• comparator() – Returns the comparator used to order the keys in the map, or null
if the map uses the natural ordering of the keys.
• firstEntry() – Returns the rst (lowest) entry in the map.
• lastEntry() – Returns the last (highest) entry in the map.

TreeMap method -

replace(K key, V Replaces the entry for a key only if it is currently


oldValue, V newValue) mapped to the specified value.
replace(K key, V Replaces the value for the key if the key is already
value) present.
putIfAbsent(K key, V Adds the key-value pair if the key is not already
value) present.

=====================================================

HastTable =
fi
fi
Does no allow Duplicate key allow Duplicate values .
Synchronised
Default size 11
No Insertion order .
No null key and values not even single key and value .
What does internally us - Uses a hash table (array of buckets) for storing key-valu
pairs
Load factory 0.75

HasHap VS HashTable -

ropert HashMa Hashtabl


y p e
Thread Not synchronized (not thread- Synchronized (thread-
Safety safe). safe).
Null Keys/ Allows one null key and multiple null Does not allow null keys or
Values values. values.
Perform Faster than Hashtable in most cases due to lack Slower due to synchronization
ance of synchronization. overhead.
Default 16 (initial 11 (initial
Capacity capacity). capacity).
Default Load
0,75 0,75
Factor
Insertion Does not maintain insertion Does not maintain insertion
Order order. order.
Resizing Doubles the capacity when the Doubles the capacity when the
Mechanism threshold is reached. threshold is reached.
Legacy Part of Java 1.2 and Part of the original version of Java (pre-Java
Status newer. 1.2).
AP Part of Part of [Link] but considered
I [Link]. legacy.
Iter fail-fast iterator (throws fail-fast iterator (throws
ato ConcurrentModificationExcep ConcurrentModificationExcep
r tion if modified while iterating). tion if modified while iterating).
Used Typically used in non-threaded Typically used in legacy systems or when thread
For environments. safety is required.
Subcl LinkedHashMap, No direct subclass for concurrency, but
asses ConcurrentHashMap (for thread ConcurrentHashMap is preferred.

ConcurrentHashMap VS HashTable VS Synchronised HashMap

Featur ConcurrentHashMa Hashtabl Synchronized


e p e HashMap
Thr Thread-safe, allows Thread-safe, locks the Thread-safe by synchronizing
ead concurrent reads and writes entire map for every every method, causing all
Safe
Perforwithout locking the entire operation,
Loweven read operationsLower
to be performance
locked.
High performance under performance in multi-
mance concurrency. Uses fine-grained threaded environments due to due to locking on
locks (segment-level locking). locking the entire map. every operation.
Null Does not allow null Does not allow null Allows null keys and values (but
Keys/ keys or values. keys or values. whole map is synchronized).
Values
Synchroniz Fine-grained locking (locks Single lock for the Locks the whole map with
ation only parts of the map, not entire map (full synchronized keyword
Mechanis the whole map). synchronization).
Resizing requires locking, for Resizing
each operation.
Resi Can resize while still requires locking,
zing allowing concurrent reads causing performance which impacts
and writes. bottlenecks. performance.
U Ideal for highly concurrent Suitable for legacy code, Suitable for legacy code where
se applications where many or where thread safety is you want a thread-safe
C threads perform read and write required but performance HashMap but without the
as operations concurrently. is not a priority. overhead of Hashtable.
Locki Uses segment-level locks or Uses a single global lock Uses synchronized
ng bucket-level locking (Java 8+). for the entire map, which methods, meaning only
Mech This allows multiple threads to means only one thread one thread can access the
anism access different
fail-safeparts of the map can access iteration;
the map at aSupports
map atfail-fast
a time for any
Fail- Supports iteration; Supports fail-fast iteration;
Safe it won't throw will throw will throw
Beh ConcurrentModifica ConcurrentModifica ConcurrentModifica
avio tionException even if tionException if the tionException if the
rInterna Internally uses a segmented hash Internally uses a Internally uses a single
l Data table where each segment has its own single hash table hash table with
Structu lock, allowing better concurrency. with a global lock. synchronization on each

Ex -

ConcurrentHashMap -

ConcurrentHashMap<String, String> concurrentMap = new


ConcurrentHashMap<>();

// Adding key-value pairs


[Link]("A", "Apple");
[Link]("B", "Banana");
[Link]("C", “Cherry");

HashTable -

// Create a Hashtable
Hashtable<String, String> hashtable = new Hashtable<>();

// Adding key-value pairs


[Link]("A", "Apple");
[Link]("B", "Banana");
[Link]("C", "Cherry");
Synchronised HashMap. -

// Create a HashMap and synchronize it


Map<String, String> hashMap = new HashMap<>();
Map<String, String> synchronizedMap =
[Link](hashMap);

// Adding key-value pairs


[Link]("A", "Apple");
[Link]("B", "Banana");
[Link]("C", "Cherry");

ConcurentHashMap internay uses. - Internally uses a segmented hash table where


each segment has its own lock, allowing better concurrency.

• A ConcurrentHashMap with 16 segments would have 16 separate locks, with each


segment having its own bucket array and lock.

• If a thread wanted to access a segment, it would acquire the lock for that segment, not for
the whole map.

Java 8+: Replaced with bucket-level locking and atomic operations for better performance and
simplicity. The map no longer uses segments internally.

Collection INterview Questions. -

You might also like