Q.1 What is the difference between == and .equals() in Java?
Ans:- == It is used to compare 2 values. It Checks if both values
refer to the same object in memory (or same primitive value)
Example a == b, we can use is for primitive data type
Example:
String a = "aditi";
String b = "aditi";
if (a == b) {
[Link]("Pranshu is pagal");
}
if([Link](b)){
[Link]("Aditi is beautiful");
}
}
}
.equals() Checks if two different objects have the same content.
Example [Link](b)
It will works on non-primitive
Example:- String a = "aditi";
String b = new String("aditi");
if (a == b) {
[Link]("Pranshu is pagal");
}
if([Link](b)){
[Link]("Aditi is beautiful");
}
}
}
Q.2 What is the difference between final, finally and finalize()?
Final- final is used for variables, methods, classes.
Variables can't be changed once it is declared as final .
Method cannot be overridden and classes cannot be extended once it
is declared as final.
Finally- Finally is used with TRY-CATCH block. Finally block always
executes – whether some exception occurs or not.
Finally even executes if there’s a return statement in try or catch.
Finalize- Finalize is a method defined in Object class.
Finalise is called by the Garbage Collector before deleting an
object from memory, to give it a chance to clean up resources.
Finalise is called by the Garbage Collector before deleting an
object from memory, to give it a chance to clean up resources.
Q.3 What is a functional interface? Give an examplE
Ans:-A functional interface is an interface which have multiple
default or static methods and exactly one abstract method.
Functional interfaces are the basis of Lambda Expressions and Method
References in Java .
They are annotated with @FunctionalInterface (optional, but helps
the compiler enforce the rule).
Example:-
Java already provides many functional interfaces in the
[Link] package, such as:
Runnable → void run()
Callable<V> → V call()
Predicate<T> → boolean test(T t)
Function<T, R> → R apply(T t)
Consumer<T> → void accept(T t)
Supplier<T> → T get()
Q.4 What is the purpose of the static key?
Ans:- Static keyword is used with variable and methods.
Static Variable and method belongs to the class itself not to object
of the class
They are initialised at the compile time and a single copy of the
variable and method are shared across all the instance of the class.
I have used it in my project:
- static variables Used for shared constants like URL paths, config
values, or error messages
- static methods we used to load json files stored in resources.
Q.5 Explain method overloading vs method overriding.
Ans :- Method Overriding - In the case of Inheritance if the child
class and parent class have methods with same name then at the run
time it decides which method to call.
Method Overloading - Methods with same signature but different
parameters. 2 or more methods can have same name but different
parameters.
Based upon the type of parameter passed ,compiler decides Which
method is called.
Q.6 What is the difference between an abstract class and an
interface?
Ans:- Abstract classes are incomplete classes as they contains
abstract methods and we can not create object for such class.
Abstract class is a base class
It can have variable and methods that can be used by all child
classes.
It can use constructor of child class to initialise variables.
Interface:-An interface define a contract or a set of abstract
method that a class must implement.
We use it when we want to define a contract that multiple classes
should follow.
It is used When we want enable polymorphism & abstraction.
It cannot have variables but it can have constants that are given
at
compile time only and it cannot have constructor.
Q.7 What is the diamond problem in Java? How is it resolved?
Ans:- A
/ \
B C
\ /
D
Class B and C both inherit from A.
Class D inherits from both B and C.
The Problem:
If both B and C override a method from A, and D inherits from both,
which version should D use? This ambiguity is the diamond problem.
Java allows multiple inheritance with interfaces, as interfaces can
have default methods (since Java 8). This can lead to a diamond-like
situation.
Use [Link]() to choose one method and resolve
the conflict.
Q.8 What are default methods in interfaces?
Ans:- Default method introduced in java 8 Using this we can have a
method in the interfaces as well.
Difference between method and default method
Default method can be used in the interface only and it uses
constants and not variables because interface cannot store variable
so it stores constants.
Normal method can be abstract but default method cannot be abstract.
Q.9:- What is a Java Stream API? Give an example use case.
Ans:- The Java Stream API, introduced in Java 8, provides a powerful
and declarative way to process
collections of data (like List, Set, etc.) using a functional
programming approach.
Streams allows us to:
- Perform operations like filtering, mapping, sorting, and
collecting
- Streams Chain these operations into a pipeline
- and Avoid writing loops manually
Example:
Real-World Use Case Example
Suppose you have a list of products and you want to:
Filter products that cost more than ₹500
Sort them by name
Collect their names into a new list
Q.10 How does Java handle memory management? Explain the garbage
collector.
Ans:-Java handles memory management automatically using a system
called Java Memory Model and Garbage Collection (GC).
🔧 Java Memory Management Overview
Java memory is divided into five main areas:
Heap:
Stores objects and class instances.
Most of the garbage collection happens here.
Stack:
Stores method calls and local variables.
Memory is allocated and deallocated in LIFO (last-in-first-out)
order.
Method Area (or Metaspace in Java 8+):
Stores class metadata, static variables, and method definitions.
Program Counter (PC) Register:
Stores the address of the current executing instruction for a
thread.
Native Method Stack:
Used for native method calls (methods written in languages like C/C+
+).
🧹 Java Garbage Collector (GC)
Garbage collection is Java’s way of automatically freeing memory
used by objects that are no longer reachable.
✅ How it works:
Using finalise method it will perform cleaning of object before the
destruction .
Object Creation:
Objects are created on the heap using the new keyword.
Reachability:
The GC checks for unreachable objects—those that can’t be accessed
by any active references.
Collection:
Unreachable objects are automatically deleted to free up memory.
Finalization (optional):
If an object overrides the finalize() method, it gets a chance to
clean up resources before being collected (though this is deprecated
in recent versions).
Q.11 What is the difference between ArrayList and LinkedList?
Ans:- 🔹 1. Storage Structure
ArrayList → Uses a dynamic array internally.
LinkedList → in linklist it store the address of next nodes
🔹 2. Memory Allocation
ArrayList → Stores elements in contiguous memory.
LinkedList → Stores elements anywhere in memory, but links them via
pointers.
🔹
4. Insertion & Deletion
ArrayList →
Adding at the end → Fast (Amortized O(1)).
Adding/Removing in the middle/start → Slow (O(n)) because elements
must be shifted.
LinkedList →
Adding/Removing at start or middle → Fast (O(1)).(if node reference
known)
But finding the position costs O(n) (big O of N) time complexity.
🔹 5. Memory Usage
ArrayList → Less memory (just data).
LinkedList → More memory (extra pointers for each node).
🔹 6. Iteration
ArrayList → Better for simple iteration (cache-friendly, elements
are continuous).
LinkedList → Slower iteration (jumps around in memory).
🔹 7. When to Use
ArrayList → Best when you need fast random access and more reads
than writes.
LinkedList → Best when you need frequent insertions/deletions,
especially in the middle or beginning.
Q.12 Explain HashMap internals — how does it work?
Ans:- Hashmap contains list of buckets, each bucket is made up of
linked list nodes.
Storing in Hashmap :
To store Key-value in Hashmap For this 1st we find the hash value
of the key using [Link]() method then
we need to find the index of the bucket in which key-value will be
stored.
hash is modulo by the number of buckets to get the index of the
bucket where key-value will be stored.
Int index = hash % capacity;
Collison in Hashmap:
A collision happens when two different keys generate the same bucket
index in the internal array
(i.e., hash % capacity gives the same result).
Java handling it:
Each bucket in the HashMap is a linked list of nodes. So, if
multiple keys map to the same index, they are stored in a chain.
We can iterate through the chain to find the desired key
*Q.13 What is immutability? How do you create an immutable class?
Ans:- Immutability means:
Once an object is created, its state (data) cannot be changed.
So if you create an immutable object, you cannot modify its fields —
not even accidentally.
🧠 Why Use Immutable Classes?
Immutable classes cannot be changed and are thread-safe by default
so no
synchronization is needed.
Can be used safely in caches, collections, and multithreaded code.
Examples of Immutable Classes in Java:
String
Integer
LocalDate
BigDecimal
🏗 How to Create an Immutable Class in Java
✅ Steps:
Make the class final — so it can't be extended
Make all fields private and final
Don't provide setters
Initialize fields via constructor
If fields are mutable (like Date or List), return a deep copy
Q.15 What is the synchronized keyword used for?
Ans:- The synchronized keyword is used to prevent multiple threads
from accessing a block of code or a method at the same time which
could lead to inconsistent or corrupt data.
Why Use synchronized?
To ensure only one thread can execute a critical section of code at
a time — this helps avoid race conditions.
How it Works:
Every object in Java has a monitor lock (also called intrinsic
lock).
When a thread enters a synchronized method/block:
It acquires the lock on the object
Other threads trying to enter must wait
Once the thread exits the synchronized section, it releases the
lock.
Q. 16 What is oops?
Ans:- Abstraction- In abstraction internal complex implementation
are hidden and only the needed information is shown.
It is achived using interfaces and abstract
classes
Interfaces: In case of interface the child class
contains the implementation logic which is hidden and we call the
child class using the interface.
Abstract class- So in abstract class we can have
a method with the implementation and we can use child class object
to call that method
Inheritance- In inheritance Child class inherit the properties of
parents class.
It has 4 different types:
Single:- single child class inherit the properties of single parent
class
Multi-level :- there is multiple Levels of inheritance for example B
class inherits A and C class inherits B
Hierarchy:- More than 1 child class inherits the properties of same
parent class.
Multiple:- Single child class inherit the properties of more than 1
parent class.
It is achievable using interface and using super keyword.
Polymorphism: poly means multiple form single method can do multiple
things
It has two different types
Run time
Compile time
Run time is also known as method overriding. The child class and
parent class can have same method name and at the run time it will
decide which method will be called.
Compile time is also known as method overloading and the method have
same signature with different parameters.
Encapsulation: it means wrapping data and methods together into a
single unit and restricting direct access.
Q. 17 Define Hashset hashtable list?
Ans:- Hashset:- HashSet is a class in Java that implements the Set
interface.
It is used to store a collection of unique elements
(no duplicates allowed).
It is backed internally by a HashMap.
Hash table:- t stores key–value pairs, similar to HashMap.
All its methods are synchronized, meaning it can be safely used in
multi-threaded environments.
List:-List is an interface in Java (part of the Collections
Framework).
It represents an ordered collection of elements, meaning:
Elements are stored in sequence (insertion order maintained).
Duplicate elements are allowed.
Elements can be accessed by their index (like an array).
Q.18 Difference between hashtable and Hashmat
Ans:- HashMap
Hashtable
Introduced in- Java 1.2 (Collections Framework) Java 1.0
(Legacy class)
Thread-Safety- ❌ Not synchronized (not thread-safe) ✅
Synchronized (thread-safe)
Performance- Faster (no synchronization overhead) Slower
(because of synchronization)
Null Keys- Allows 1 null key ❌ Does not
allow null key
Null Values- Allows multiple null value ❌ Does not
allow null values
Usage- Best for single-threaded application Can be used in
multi-threaded apps,but outdated
Preferred Alternative- Use HashMap normally Use
ConcurrentHashMap instead of Hashtable
Q.19 Define Stack and Queue
Ans:- Stack :- A Stack is a linear data structure that follows the
LIFO (Last In, First Out) principle.
The last element inserted is the first one removed.
Think of it like a stack of plates: the last plate placed on top is
the first one you take out.
Main Operations
push(element) → Add element to the top.
pop() → Remove element from the top.
peek() → View the top element without removing it.
isEmpty() → Check if stack is empty.
Queue:-A Queue is a linear data structure that follows the FIFO
(First In, First Out) principle.
The first element inserted is the first one removed.
Think of it like a line at a ticket counter: the first person in
line gets served first.
Main Operations
add(element) / offer(element) → Insert element at the rear.
remove() / poll() → Remove element from the front.
peek() → View the front element without removing it.
isEmpty() → Check if queue is empty.
Q20. Define multi threading?
Ans:- Multithreading in Java is a feature that allows multiple
threads (small units of a process) to run concurrently within a
program.
It helps in doing multiple tasks at the same time, improving
performance and resource utilization.
Key Points
Concurrency → Multiple threads can run in parallel (not necessarily
at the same instant, but managed by CPU scheduling).
Lightweight → Threads share the same memory space of the process.
Better performance → Especially on multi-core processors.
Independent tasks → Each thread runs independently, but they can
communicate if needed.
Example in Real Life
A web browser:
One thread loads text.
Another loads images.
Another plays a video.
Q.21 What is Contructor? Types of contractor
Ans: It is a special method use to initialize object.
It sets initial values for the object properties
Default constructor:- It assigns default values to object parameters
Parametrized constructor - parameters are passes along with the
constructor
Copy constructor- it is used to make copy of an object
Two difference types of it:-
Shallow copy- In shallow copy non-primitive variables are present
few of the variables are shared between objects.
Deep copy- No variable of class is shared between objets.
*Difference between shallow copy / Deep copy
Shallow Copy 👉 Makes a new object, but if the object has other
objects inside it (like lists inside a list), it only copies
references (links) to them, not the actual inner objects.
Deep Copy 👉 Makes a new object and also copies everything inside
it separately, so changes in one do not affect the other.
In short:
Shallow copy = copy outer shell, share inner stuff.
Deep copy = copy everything, no sharing.
On the base of memory
Shallow Copy (Memory level)
A new object is created in memory.
But the inner objects are not copied, only their memory addresses
(references) are copied.
So, both the original and shallow copy point to the same inner
objects in memory.
👉 That’s why if you change the inner object from one copy, it also
changes in the other.
🔵 Deep Copy (Memory level)
A new object is created in memory.
And for all inner objects, new memory is allocated and their
contents are recursively copied.
So, original and deep copy have completely different memory
addresses for everything.
👉 That’s why changing one does not affect the other.
💡 Think of it like this:
Shallow copy → “Copy the box, but both boxes share the same items
inside.”
Deep copy → “Copy the box and also make new copies of all items
inside.”
***************
Class:- blueprint of object
-It stores properties of object as variables and functions /
behavioural as methods.
Object:-Instance of class
-Real life entities such as table, class, student
Q. Why we use default method?
Ans:- Before java 8 All the interface were abstract methods and
classes implementing the interface need to
implement abstract method .so adding new method to interface would
break the
existing classes using that interface or we have to implement that
method in all the classes
After java 8 , default methods were added in interface which had a
body . So the implementing classes had the option to use that method
by overriding.
Basically we can add new method in Interface without breaking
existing code