Java Interview Questions & Answers
Interview-Focused | Concept-Oriented | Real-Time Examples
Prepared By: Revanth
Technology: Core Java & Advanced Java
Purpose: Interview Preparation
Audience: Freshers & Experienced Professionals
🎯 Purpose of This Document
The purpose of this document is to provide commonly asked Java interview
questions with clear, concise, and accurate answers from an interviewer’s
perspective.
⚠️Disclaimer
The questions included in this document are collected from real interview
experiences, industry standards, and common interview patterns.
Answers are prepared for educational and interview preparation purposes
only.
Interview questions may vary depending on the company, role, and
experience level.
This document does not guarantee selection but aims to improve conceptual
clarity and confidence.
Thanks for Using This Document
Best of luck for your Java interviews 🚀
Keep practicing, keep learning, and stay confident.
Q.1 What is the difference between JDK and JRE?
JRE (Java Runtime Environment): It is the minimum requirement for
running a Java application. It includes the JVM (Java Virtual Machine)
and core libraries.
JDK (Java Development Kit): It is a superset of JRE. It contains
everything in the JRE plus development tools like the compiler (javac),
debugger, and Javadoc to create and compile Java programs.
Q.2 Why is Java a platform-independent language?
Java is platform-independent because of its Bytecode. When you compile Java code, it isn't
converted into machine code for a specific OS; instead, it's converted into Bytecode (.class files).
This Bytecode can run on any system that has a JVM installed, following the philosophy: "Write
Once, Run Anywhere" (WORA).
Q.4 What is the difference between final, finally, and finalize?
final: A keyword used to apply restrictions. A final class cannot be
inherited, a final method cannot be overridden, and a final variable
cannot be changed.
finally: A block used with try-catch to execute important code (like
closing resources) regardless of whether an exception is handled or
not.
finalize(): A method of the Object class called by the Garbage
Collector just before an object is destroyed to perform cleanup. (Note:
It is now deprecated in newer Java versions).
Q.5 What is the difference between stack and heap memory?
Stack Memory: Used for static memory allocation and the execution
of a thread. it stores primitive variables and references to objects. It
follows Last-In-First-Out (LIFO) order.
Heap Memory: Used for dynamic memory allocation. All Java objects
are stored here. It is much larger than the stack and is managed by the
Garbage Collector.
Q.6 What is the difference between method overloading and
method overriding?
Overloading: Occurs in the same class when two methods have the
same name but different parameters (Compile-time polymorphism).
Overriding: Occurs in a subclass when it provides a specific
implementation for a method already defined in its parent class
(Runtime polymorphism).
Q.7 (Repeated in Image) What is the difference between private
and protected modifier?
private: Members are accessible only within the same class.
protected: Members are accessible within the same package and also
by subclasses in different packages.
Q.8 What is constructor overloading in Java?
Constructor overloading is a technique of having more than one constructor with different
parameter lists in the same class. It allows the class to be initialized in different ways depending
on the data provided at the time of object creation.
Q.9 What is the use of the super keyword in Java?
The super keyword is a reference variable used to refer to immediate parent class objects. It is
used to:
1. Call parent class methods that have been overridden.
2. Access parent class instance variables.
3. Invoke the parent class constructor (must be the first line in the child
constructor).
Q.10 What is the difference between static methods, static
variables, and static classes?
Static Variable: Shared among all instances of a class; memory is
allocated only once when the class is loaded.
Static Method: Belongs to the class rather than the object. It can be
called without creating an instance and can only access other static
members.
Static Class: Java only allows Nested Static Classes. You cannot
make a top-level class static. A static nested class does not need a
reference to the outer class.
Q.11 What exactly is [Link] in Java?
System: Is a final class in [Link] package.
out: Is a static member of the System class and is an instance of
PrintStream.
println: Is a method of the PrintStream class used to print to the
console.
Q.12 What part of memory—Stack or Heap—is cleaned in the
garbage collection process?
The Heap memory is the only part cleaned by Garbage Collection. The Stack memory is
automatically managed—when a method finishes execution, its "frame" (including local
variables) is popped off the stack immediately.
Object-Oriented Programming (OOPs)
Q.1 What are the Object Oriented Features supported by Java?
Abstraction: Hiding internal details and showing only functionality.
Encapsulation: Binding code and data together into a single unit
(class).
Inheritance: Mechanism where one object acquires all properties and
behaviors of a parent object.
Polymorphism: The ability of a variable, function, or object to take on
multiple forms (Overloading and Overriding).
Q.2 What are the different access specifiers used in Java?
Public: Accessible everywhere.
Protected: Accessible within the same package and by subclasses.
Default (no modifier): Accessible only within the same package.
Private: Accessible only within the same class.
Q.3 What is the difference between composition and inheritance?
Inheritance: Represents an "IS-A" relationship (e.g., a Car is a
Vehicle). It is a tight coupling.
Composition: Represents a "HAS-A" relationship (e.g., a Car has an
Engine). It is considered more flexible than inheritance.
Q.4 What is the purpose of an abstract class?
To provide a common template for subclasses and achieve partial
abstraction.
It cannot be instantiated and is used to define default behavior that
subclasses can share or override.
Q.5 What are the differences between constructor and method of
a class in Java?
Constructor: Used to initialize an object; has no return type; name
must match the class name.
Method: Used to define the behavior of an object; must have a return
type (or void); name can be anything.
Q.6 What is the diamond problem in Java and how is it solved?
The diamond problem occurs when a class tries to inherit from two
classes that have a common parent, leading to ambiguity in which
method to inherit.
Solution: Java does not support multiple inheritance with classes. It is
solved using Interfaces, where a class can implement multiple
interfaces and must provide its own implementation for any conflicting
methods.
Q.7 What is the difference between local and instance variables in
Java?
Instance Variables: Declared inside a class but outside methods;
they have default values and live as long as the object lives.
Local Variables: Declared inside a method or block; they do not have
default values (must be initialized before use) and live only during
method execution.
Q.8 What is a Marker interface in Java?
An interface that has no methods or fields (e.g., Serializable,
Cloneable).
It provides run-time type information to the JVM so it can perform
specific operations on the object.
Data Structures and Algorithms
Q.1 Why are strings immutable in Java?
Security: Prevents sensitive data (like passwords) from being
changed.
String Pooling: Multiple references can point to the same string in
memory to save space.
Thread Safety: Since they cannot change, they are naturally thread-
safe.
Q.2 What is the difference between creating a String using new()
and as a literal?
Literal (String s = "abc"): Checks the String Constant Pool first. If it
exists, it reuses it; if not, it creates a new one in the pool.
new() (String s = new String("abc")): Always creates a new object
in the Heap memory, even if the string already exists in the pool.
Q.3 What is the Collections framework?
A unified architecture for representing and manipulating collections
(groups of objects).
It includes interfaces (List, Set, Map) and implementation classes
(ArrayList, HashMap, etc.).
Q.4 What is the difference between ArrayList and LinkedList?
ArrayList: Uses a dynamic array; better for searching (O(1) access);
slower for insertion/deletion (requires shifting).
LinkedList: Uses a doubly linked list; better for insertion/deletion
(O(1) if you have the pointer); slower for searching (O(n)).
Q.5 What is the difference between a HashMap and a TreeMap?
HashMap: Does not maintain any order; allows one null key; faster
(O(1) average performance).
TreeMap: Maintains sorted order (natural or custom); does not allow
null keys; slower (O(log n)).
Q.6 What is the difference between a HashSet and a TreeSet?
HashSet: No guaranteed order; backed by HashMap; faster
performance.
TreeSet: Maintains elements in sorted order; backed by TreeMap;
slower performance.
Q.7 What is the difference between an Iterator and a ListIterator?
Iterator: Can traverse elements only in the forward direction; works
with any Collection.
ListIterator: Can traverse in both forward and backward
directions; works only with Lists.
Exception Handling
Q1. What is an exception in Java?
An exception is an unwanted or unexpected event that occurs during the
execution of a program and disrupts the normal flow of the application.
In Java, exceptions are handled using try, catch, finally, throw, and throws
keywords.
👉 Example: NullPointerException, ArithmeticException
Q2. How does an exception propagate throughout the Java code?
Exception propagation means when an exception occurs in a method and is
not handled there, it is passed to the calling method, and this continues until
it is handled or reaches the JVM.
👉 If no method handles it, the JVM terminates the program.
Q3. What is the difference between checked and unchecked exceptions?
Checked Exception Unchecked Exception
Checked at compile time Checked at runtime
Must be handled using try-catch or throws Handling is optional
Extends Exception Extends RuntimeException
Example: IOException, SQLException Example: NullPointerException,
ArithmeticException
Q4. What is the use of try-catch block in Java?
The try-catch block is used to handle runtime errors so that the program
does not terminate abruptly.
Try → risky code
Catch → handling code
This improves program reliability and stability.
Q5. What is the difference between throw and throws?
Throw throws
Used to explicitly throw an exception Used to declare exceptions
Used inside a method Used in method signature
Throws a single exception Can declare multiple exceptions
Example: throw new Exception() Example: throws IOException
Q6. What is the use of the finally block?
The finally block is used to execute important cleanup code, such as closing
database connections or files.
👉 It always executes, whether an exception occurs or not (except
[Link]()).
Q7. What is the base class of all exception classes?
The base class of all exception classes in Java is [Link].
Hierarchy:
Throwable
├── Exception
│ └── RuntimeException
└── Error
Q8. What is Java Enterprise Edition (Java EE)?
Java EE (now called Jakarta EE) is used to build enterprise-level, scalable, and
distributed applications like web and backend systems.
It provides APIs such as:
Servlets
JSP
JPA
EJB
👉 Mainly used for web applications and enterprise solutions.
Multithreading – Java Interview Questions & Answers
Q1. What is a thread and what are the different stages in its lifecycle?
Answer:
A thread is a lightweight sub-process that allows multiple tasks to run
concurrently within a program.
Thread Lifecycle Stages:
New – Thread is created
Runnable – Ready to run
Running – CPU allocated
Waiting / Timed Waiting – Waiting for resources or time
Terminated (Dead) – Execution completed
Q2. What is the difference between a process and a thread?
Process
Thread
Heavyweight
Lightweight
Has separate memory
Shares same memory
Slower creation
Faster creation
Inter-process communication is costly
Communication is faster
More resource consumption
Less resource consumption
Q3. What are the different types of thread priorities available in Java?
Answer:
Java supports three thread priorities:
MIN_PRIORITY → 1
NORM_PRIORITY → 5 (default)
MAX_PRIORITY → 10
👉 Priority decides execution preference, not execution guarantee.
Q4. What is context switching in Java?
Answer:
Context switching is the process where the CPU switches from one thread to
another to provide multitasking.
👉 It helps achieve concurrency, but frequent switching can reduce
performance.
Q5. What is the difference between user threads and daemon threads?
User Thread
Daemon Thread
Executes main logic
Provides background services
JVM waits for completion
JVM doesn’t wait
Examples: main thread
Examples: Garbage Collector
Q6. What is synchronization?
Answer:
Synchronization is used to control access to shared resources and avoid data
inconsistency in a multithreaded environment.
👉 Achieved using:
Synchronized keyword
Synchronized methods or blocks
Q7. What is a deadlock?
Answer:
Deadlock is a situation where two or more threads wait indefinitely for each
other’s resources, causing the program to freeze.
👉 Occurs when:
Mutual exclusion
Hold and wait
No preemption
Circular wait
Q8. What is the use of the wait() and notify() methods?
Answer:
Wait() → Causes the current thread to release the lock and wait
Notify() → Wakes up one waiting thread
notifyAll() → Wakes up all waiting threads
👉 Used for inter-thread communication and must be called inside a
synchronized block.
Additional Multithreading Interview Questions
Q9. What is the difference between a thread and a process in Java?
Answer:
A process has its own memory space, while threads share the same memory
within a process, making threads faster and more efficient.
Q10. What is the difference between synchronized and volatile in Java?
Synchronized
Volatile
Ensures mutual exclusion
Ensures visibility
Thread-safe
Not fully thread-safe
Uses locking
No locking
Slower
Faster
Q11. What is the purpose of the sleep() method in Java?
Answer:
Sleep() is used to pause the execution of a thread for a fixed time.
👉 It does not release the lock and is a static method of Thread class.
Q12. What is the difference between wait() and sleep()?
Wait()
Sleep()
Releases lock
Does not release lock
Called on Object class
Called on Thread class
Used for communication
Used for delay
Q13. What is the difference between notify() and notifyAll()?
Answer:
Notify() → Wakes up one random waiting thread
notifyAll() → Wakes up all waiting threads
👉 Used to prevent deadlock in complex scenarios.
🙏 Thank You
Thank you for taking the time to go through this Java Interview Questions &
Answers document.
We hope it helps you build strong conceptual clarity, interview confidence,
and succeed in your technical interviews.
🔔 Follow for More