JAVA - Interview Questions
JAVA - Interview Questions
Answer:
● JRE (Java Runtime Environment): Includes JVM and required libraries to run Java
applications.
● JDK (Java Development Kit): A superset of JRE containing development tools such as
the compiler, debugger, and JavaDoc for writing and compiling Java programs.
✅ Code Example:
java
✅ Real-world Example:
JDK is like a kitchen (tools to cook), JRE is the stove + ingredients, JVM is the flame that
cooks the recipe.
Answer:
The four core principles are:
1. Encapsulation – Bundling data and methods that operate on that data.
2. Abstraction – Hiding internal implementation and exposing only essential features.
3. Inheritance – Mechanism for one class to acquire the properties of another.
4. Polymorphism – Ability of different classes to respond to the same method call in
different ways.
✅ Code Example:
java
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
✅ Real-world Example:
A remote control represents abstraction (you press without knowing internals), supports
polymorphism (same button, different TV brands), and all remotes inherit from a basic design.
Answer:
● == compares memory references, i.e., whether two object references point to the same
memory location.
✅ Code Example:
java
✅ Real-world Example:
Two identical books: == checks if both are same physical book, .equals() checks if they
have same content.
Answer:
Strings are immutable to ensure security, thread safety, caching (String Pool), and to avoid
unexpected behavior when used as keys in hash-based collections.
✅ Code Example:
java
String s1 = "Hello";
String s2 = s1;
s1 = "World";
System.out.println(s2); // Output: Hello
✅ Real-world Example:
A sealed glass bottle – once filled (created), contents can’t be changed. Any change results in
a new bottle.
Answer:
✅ Real-world Example:
● String is like a printed photo – permanent.
● StringBuilder is a whiteboard.
Answer:
● Overloading: Defining multiple methods with the same name but different parameter
lists within the same class. It supports compile-time polymorphism.
✅ Code Example:
java
class A {
void display(int a) {}
void display(String b) {}
}
class B extends A {
@Override
void display(int a) {} // Overriding
}
✅ Real-world Example:
ATM machine:
● Overloading – withdraw via card, UPI, or fingerprint (same action, different ways).
● Overriding – Different banks implement the withdrawal process in their own way.
Answer:
● Abstract class: Can have method definitions, instance variables, constructors. Supports
partial abstraction.
● Interface: Fully abstract (until Java 8), used to define a contract that classes must
implement. Supports multiple inheritance.
✅ Code Example:
java
interface Flyable {
void fly();
}
✅ Real-world Example:
● Abstract class: A blueprint for a general type (e.g., Vehicle).
● Interface: A plug/socket standard – anything that fits must behave in a certain way.
8. What are access modifiers in Java?
Answer:
Access modifiers define the scope of visibility for classes, methods, and variables:
✅ Code Example:
java
✅ Real-world Example:
In a house:
Answer:
● Static methods belong to the class and can be called without an object.
✅ Code Example:
java
class Sample {
static void showStatic() {
System.out.println("Static");
}
void showNonStatic() {
System.out.println("Non-Static");
}
}
✅ Real-world Example:
Static is like a company rulebook – same for all employees.
Non-static is like employee ID cards – unique for each person.
Answer:
Constructor chaining is the process of calling one constructor from another using this() or
calling the parent class constructor using super(). It promotes code reusability and cleaner
initialization.
✅ Code Example:
java
class Demo {
Demo() {
this(10);
System.out.println("Default Constructor");
}
Demo(int x) {
System.out.println("Parameterized Constructor");
}
}
✅ Real-world Example:
When buying a laptop, the base model includes OS, and chaining adds RAM, storage,
warranty step by step.
Answer:
● ArrayList uses a dynamic array; supports fast random access but slow
insertion/deletion (except at the end).
✅ Code Example:
java
✅ Real-world Example:
● ArrayList is like a train – you can jump to any coach easily, but inserting one in the
middle is hard.
● LinkedList is like a chain – easy to add/remove links, but tough to reach the middle.
12. What is the difference between HashMap and Hashtable?
Answer:
● HashMap is non-synchronized, allows one null key and multiple null values.
✅ Code Example:
java
✅ Real-world Example:
● HashMap is like a notebook anyone can write in.
● Hashtable is like a locker diary – only one person at a time can use it, and it rejects
blank keys.
Answer:
HashMap stores data as key-value pairs using an array of buckets.
● If a collision occurs, it stores entries in a linked list (or tree in Java 8+ for large
collisions).
✅ Real-world Example:
Think of a library where books (values) are placed by category code (key hash). If multiple
books share a shelf, they're arranged in a list or stack.
Answer:
✅ Code Example:
java
✅ Real-world Example:
● HashSet is like a basket where you throw items randomly.
Answer:
The Collections framework is a unified architecture for storing and manipulating data in Java. It
includes interfaces (List, Set, Map) and their implementations (ArrayList, HashSet, HashMap)
with utility classes like Collections and Arrays.
✅ Code Example:
java
✅ Real-world Example:
Think of the Collections framework as a toolbox containing different tools (List, Set, Map) for
different storage needs.
Answer:
● ListIterator can traverse both directions and modify elements (only for List).
✅ Code Example:
java
✅ Real-world Example:
● Iterator is like a one-way ticket – move forward only.
● ListIterator is a two-way ticket – go forward and backward
17. What is the difference between Comparable and Comparator?
Answer:
✅ Code Example:
java
✅ Real-world Example:
● Comparable: Ranking students by roll number.
Answer:
HashSet does not allow duplicate elements. If a duplicate is added, it is silently ignored
based on the result of hashCode() and equals().
✅ Code Example:
java
✅ Real-world Example:
A guest list app – if the same name is entered twice, only one entry is stored.
Answer:
● Set does not allow duplicates and may or may not maintain order (e.g., HashSet vs
TreeSet).
✅ Code Example:
java
✅ Real-world Example:
● List is like your shopping list – can have repeated items.
Answer:
● Array has a fixed size and can store both primitives and objects.
● ArrayList is dynamic and can only store objects (uses wrapper classes for primitives).
✅ Code Example:
java
✅ Real-world Example:
● Array is like a fixed-size train – once built, can’t add more coaches.
● ArrayList is like a bus that expands when more passengers get in.
Answer:
Exception handling is a mechanism to handle runtime errors gracefully without crashing the
program. It helps maintain the program flow using constructs like try, catch, throw, throws,
and finally.
✅ Code Example:
java
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
✅ Real-world Example:
Like an airbag in a car — catches errors (accidents) and ensures minimal damage to flow.
Answer:
✅ Code Example:
java
// Checked
public void readFile() throws IOException {}
// Unchecked
int a = 10 / 0;
✅ Real-world Example:
● Checked: You must wear a helmet (rule).
Answer:
✅ Real-world Example:
● throw: You throw the ball (raise exception).
Answer:
The finally block is always executed after the try and catch blocks, regardless of whether
an exception was thrown or caught. It is commonly used for cleanup operations like closing files
or releasing resources.
✅ Code Example:
java
try {
int a = 5 / 0;
} catch (Exception e) {
System.out.println("Caught");
} finally {
System.out.println("Finally block executed");
}
✅ Real-world Example:
Like a clean-up crew after a party — comes in no matter what happened.
25. Can we have multiple catch blocks for a single try block?
Answer:
Yes, Java allows multiple catch blocks to handle different types of exceptions separately from
a single try block.
✅ Code Example:
java
try {
int[] arr = new int[2];
System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array error");
} catch (Exception e) {
System.out.println("General error");
}
✅ Real-world Example:
Different first aid kits for different injuries — each exception has a specific fix.
Answer:
✅ Code Example:
java
@Override
protected void finalize() throws Throwable {
System.out.println("Finalized");
}
✅ Real-world Example:
● final – sealed envelope
Answer:
Multithreading is the process of executing multiple threads simultaneously to achieve
parallelism. It improves performance in tasks like gaming, real-time apps, or network
programming.
✅ Code Example:
java
✅ Real-world Example:
Like a restaurant kitchen with multiple chefs working on different dishes at once.
28. What is the difference between Thread class and Runnable interface?
Answer:
● Extending Thread class means your class cannot extend any other class.
✅ Code Example:
java
✅ Real-world Example:
● Thread: Full-time worker.
Answer:
Synchronization is used to control access to shared resources in multithreaded environments,
preventing data inconsistency by allowing only one thread at a time.
✅ Code Example:
java
Answer:
● sleep() pauses the current thread for a specific time but doesn't release the lock.
● wait() pauses the thread and releases the lock until notify() or notifyAll() is
called.
✅ Code Example:
java
Thread.sleep(1000); // 1 second
synchronized(obj) {
obj.wait();
}
✅ Real-world Example:
● sleep(): You take a nap but keep your key (lock).
● wait(): You pause and hand over the key, waiting for a signal to continue.
Answer:
A deadlock occurs when two or more threads are blocked forever, each waiting for a resource
held by the other.
It can be avoided by:
✅ Code Example:
java
synchronized(lock1) {
synchronized(lock2) {
// potential deadlock if another thread reverses order
}
}
✅ Real-world Example:
Two people trying to enter each other's rooms at the same time, both holding their own keys
and waiting forever.
Answer:
The volatile keyword ensures that a variable's value is always read from the main
memory, not from thread-local caches. It guarantees visibility but not atomicity.
✅ Code Example:
java
✅ Real-world Example:
Like a digital scoreboard – everyone sees the latest score immediately, no local guesswork.
33. What is the difference between heap and stack memory?
Answer:
● Stack memory stores local variables and method call frames. It is fast and thread-safe.
● Heap memory is used for dynamic memory allocation of objects and shared among
threads.
✅ Code Example:
java
int x = 5; // Stack
String s = new String("Java"); // Heap
✅ Real-world Example:
● Stack is your working desk – quick access, small, temporary.
Answer:
Garbage Collection (GC) automatically frees memory by removing objects that are no longer
reachable. Java uses algorithms like Mark and Sweep, and GC runs in background threads.
✅ Code Example:
java
obj = null;
System.gc(); // Hint to run GC (not guaranteed)
✅ Real-world Example:
A maid cleaning unused items from a room to free space.
35. What is the difference between shallow copy and deep copy?
Answer:
● Shallow copy copies object references; changes in original affect the copy.
● Deep copy creates a new object and recursively copies all fields.
✅ Code Example:
java
✅ Real-world Example:
● Shallow: Two photocopies of a file shortcut – both point to same file.
● Deep: Two independent printed documents – change one, other remains same.
Answer:
Wrapper classes convert primitive data types into objects. Examples: int → Integer,
char → Character.
They allow primitives to be used in collections, generics, etc.
✅ Code Example:
java
int a = 10;
Integer obj = Integer.valueOf(a);
✅ Real-world Example:
Like putting a gift (primitive) inside a box (object) to carry or store.
37. What is autoboxing and unboxing?
Answer:
✅ Code Example:
java
int a = 5;
Integer obj = a; // autoboxing
int b = obj; // unboxing
✅ Real-world Example:
Like a vending machine – you insert a coin (primitive), it goes inside a container (box), and
gives it back as a coin when needed.
38. What are generics in Java and why are they used?
Answer:
Generics allow type safety and code reusability by enabling classes and methods to operate
on objects of specified types. Introduced to eliminate typecasting and runtime errors.
✅ Code Example:
java
✅ Real-world Example:
Like a water bottle labeled for water only – prevents putting in other liquids.
39. What are lambda expressions in Java 8?
Answer:
Lambda expressions are a concise way to represent anonymous functions. They simplify
code by reducing boilerplate, mainly used in functional interfaces (interfaces with one abstract
method).
✅ Code Example:
java
✅ Real-world Example:
Like giving someone a sticky note with one instruction instead of typing a full letter.
Answer:
Stream API provides a functional approach to process sequences of elements (collections)
using filtering, mapping, and reduction operations. It supports parallel processing and is lazily
evaluated.
✅ Code Example:
java
✅ Real-world Example:
Like a factory assembly line – items go through stages (filter, map) before final output.
41. What are functional interfaces in Java?
Answer:
A functional interface is an interface with exactly one abstract method. It can have multiple
default or static methods and is used primarily with lambda expressions.
✅ Code Example:
java
@FunctionalInterface
interface Greet {
void sayHello();
}
✅ Real-world Example:
Like a remote with only one button – you can assign a specific action (lambda) to it.
Answer:
Optional is a container object that may or may not contain a non-null value. It helps in
avoiding NullPointerExceptions and represents absent values gracefully.
✅ Code Example:
java
✅ Real-world Example:
Like a gift box that may or may not contain a gift — and you're forced to check safely.
43. What is the Stream API in Java 8?
Answer:
Stream API provides a functional-style approach to process data from collections using
operations like filter, map, reduce, etc.
It supports lazy evaluation and parallel processing.
✅ Code Example:
java
✅ Real-world Example:
A production conveyor belt where items go through multiple filters and are processed in
order.
Answer:
Method reference is a shorthand for calling methods using :: operator. It improves code
readability and is used with functional interfaces.
✅ Code Example:
java
✅ Real-world Example:
Instead of typing directions, you just point to a guidebook page – quick and clear.
45. What is the difference between Serialization and Deserialization?
Answer:
✅ Code Example:
java
✅ Real-world Example:
Like saving a game and later loading it back with exact state restored.
Answer:
transient is used to indicate that a field should be excluded from serialization. It marks
data that shouldn't be persisted.
✅ Code Example:
java
✅ Real-world Example:
Like choosing what not to pack when moving — some private or irrelevant stuff stays behind.
47. What is reflection in Java?
Answer:
Reflection is an API in Java that allows inspection and modification of classes, methods, and
fields at runtime, even if they’re private.
✅ Code Example:
java
✅ Real-world Example:
Like a security camera that sees behind locked doors — lets you observe or manipulate
hidden parts.
Answer:
✅ Code Example:
java
class Engine {}
class Car {
Engine engine; // Composition
}
✅ Real-world Example:
● Inheritance: A Dog is an Animal
● Composition: A Car has an Engine
49. What is encapsulation and how do you achieve it?
Answer:
Encapsulation is the process of hiding internal state and only exposing behavior via public
methods. It's achieved by using private fields and public getters/setters.
✅ Code Example:
java
class Person {
private String name;
✅ Real-world Example:
Like a coffee machine — you don’t see the internals, you just press a button.
Answer:
Polymorphism means "one name, many forms". In Java, it is implemented via:
✅ Code Example:
java
class Animal {
void sound() { System.out.println("Sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); } // Overriding
}
✅ Real-world Example:
The word "run" – a person runs, a program runs, a car engine runs — same word, different
behavior.
Answer:
● Static variables belong to the class and are shared across all instances.
● Instance variables belong to a specific object and are unique per instance.
✅ Code Example:
java
class Example {
static int count = 0;
int id;
}
✅ Real-world Example:
● Static: Company-wide policy (same for everyone)
Answer:
When a static method in a subclass has the same signature as in the parent class, it hides
the superclass’s method instead of overriding it.
✅ Code Example:
java
class Parent {
static void show() { System.out.println("Parent"); }
}
class Child extends Parent {
static void show() { System.out.println("Child"); } // Method
hiding
}
✅ Real-world Example:
Like having two same-named files in different folders — they don’t override each other, they
hide depending on where you look.
Answer:
✅ Code Example:
java
class Parent {
int a = 10;
}
class Child extends Parent {
int a = 20;
void display() {
System.out.println(this.a); // 20
System.out.println(super.a); // 10
}
}
✅ Real-world Example:
● this: Refers to you
Answer:
No. Private methods are not inherited, hence cannot be overridden. They are only accessible
within the class where they are declared.
✅ Code Example:
java
class A {
private void show() {}
}
class B extends A {
// This is not overriding
private void show() {}
}
✅ Real-world Example:
Like a private diary — even your children can’t inherit or read it.
Answer:
Constructor overloading means defining multiple constructors in the same class with
different parameter lists. It allows creating objects in multiple ways.
✅ Code Example:
java
class Student {
Student() {}
Student(String name) {}
Student(String name, int age) {}
}
✅ Real-world Example:
Like booking a flight — one-way, round-trip, with/without meals — all are different
constructors.
Answer:
Java automatically provides a default no-argument constructor. But once you define any
constructor, Java does not generate the default one.
✅ Code Example:
java
class Car {
// No constructor declared
}
Car c = new Car(); // works fine
✅ Real-world Example:
Like getting a free sample when you don’t ask for anything — but if you customize your order,
no sample.
57. What is the difference between default and protected access modifiers?
Answer:
● protected: Accessible within the same package and in subclasses outside the
package.
✅ Code Example:
java
✅ Real-world Example:
● default: Entry allowed for local members only
Answer:
instanceof is used to check if an object is an instance of a particular class (or
subclass/interface).
✅ Code Example:
java
String s = "hello";
System.out.println(s instanceof String); // true
✅ Real-world Example:
Like asking: “Is this fruit actually an apple?”
✅ Code Example:
java
✅ Real-world Example:
● break: You leave the room
Answer:
The switch statement is a multi-branch selection control structure that checks a variable
against multiple constant values (case) and executes the matched block.
✅ Code Example:
java
int day = 2;
switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
default: System.out.println("Other");
}
✅ Real-world Example:
Like a fan regulator – each switch setting gives a different speed (outcome).
61. What is the difference between for loop and enhanced for-each loop?
Answer:
● for loop: Gives control over index; suitable for both forward/backward traversal.
● for-each loop: Simpler syntax; used to iterate over collections/arrays without index
access.
✅ Code Example:
java
// for loop
for (int i = 0; i < arr.length; i++) { }
✅ Real-world Example:
● for: Reading book page by page using numbers.
Answer:
✅ Code Example:
java
int x = 5;
while (x < 5) { System.out.println("While"); }
✅ Real-world Example:
● while: You check weather, then decide to go out.
Answer:
A nested class is a class defined within another class.
Types:
● Local class
● Anonymous class
✅ Code Example:
java
class Outer {
class Inner {}
static class StaticNested {}
}
✅ Real-world Example:
Like a department inside a company — it can either work independently or rely on the
company.
64. What is the difference between static nested class and inner class?
Answer:
✅ Code Example:
java
✅ Real-world Example:
● Static nested: Freelancer — works independently
Answer:
An anonymous class is a class without a name, declared and instantiated in a single
expression. Often used to implement interfaces or extend classes on the spot.
✅ Code Example:
java
✅ Real-world Example:
Like a temporary contractor hired for a single job without creating full employee details.
66. What is the difference between local class and anonymous class?
Answer:
✅ Code Example:
java
void method() {
class Local {}
Runnable r = new Runnable() {
public void run() { }
};
}
✅ Real-world Example:
● Local class: Intern with name badge inside one department.
● Anonymous class: Volunteer for a single event with no official identity.
67. What is a package in Java and why is it used?
Answer:
A package is a namespace that organizes related classes and interfaces. It helps in avoiding
name conflicts and controlling access.
✅ Code Example:
java
package myapp.utils;
public class Helper {}
✅ Real-world Example:
Like putting related documents into folders — neat and conflict-free.
Answer:
The import statement is used to bring other packages/classes into the current file so you can
use them without full path names.
✅ Code Example:
java
import java.util.Scanner;
✅ Real-world Example:
Like bookmarking a contact in your phone — so you don’t need to dial the full number each
time.
Answer:
Classpath is the path where the JVM looks for .class files when executing a program. It can
include directories, JAR files, etc.
Answer:
The main method is the entry point for any Java application:
java
✅ Real-world Example:
Like the main switch in a control panel — it must work even before anything else is turned on.
Answer:
✅ Code Example:
java
// Using split
String[] words = "A B C".split(" ");
// Using StringTokenizer
StringTokenizer st = new StringTokenizer("A B C");
✅ Real-world Example:
● split() – Modern cutter with patterns
● StringTokenizer – Old-school knife, less flexible
72. What is the difference between Vector and ArrayList?
Answer:
✅ Code Example:
java
✅ Real-world Example:
● Vector: Locked safe (slow, secure)
● ArrayList: Open drawer (fast, no locks)
Answer:
✅ Code Example:
java
✅ Real-world Example:
● Stack: Pile of plates – remove last added
● Queue: People in line – serve first arrived
74. What is LinkedHashMap and when would you use it?
Answer:
LinkedHashMap is a subclass of HashMap that maintains insertion order of keys.
✅ Code Example:
java
✅ Use case:
When you want a map with predictable iteration order (like printing in the order of input).
Answer:
WeakHashMap uses weak references for keys. If a key is no longer referenced elsewhere, it’s
eligible for GC, and the entry gets removed.
✅ Code Example:
java
✅ Real-world Example:
Like storing info on a whiteboard that gets erased when no one uses the marker again.
Answer:
✅ Code Example:
java
// Fail-fast
for (String s : list) {
list.add("new"); // throws error
}
✅ Real-world Example:
● Fail-fast: Alarm rings if someone touches the system while it’s running
● Fail-safe: Allows controlled updates without disturbing operation
77. What is the difference between synchronized block and synchronized method?
Answer:
✅ Code Example:
java
void partialLock() {
synchronized(this) {
// only this part is locked
}
}
✅ Real-world Example:
● Method: Locking the entire building
● Block: Locking just one room
Answer:
ThreadLocal provides thread-local variables. Each thread has its own independent copy of
the variable.
✅ Code Example:
java
✅ Real-world Example:
Like personal notebooks — each person (thread) writes without interfering with others.
Answer:
✅ Code Example:
java
synchronized(obj) {
obj.notify(); // only one thread wakes
obj.notifyAll(); // all threads wake
}
✅ Real-world Example:
● notify(): You tap one friend to wake
● notifyAll(): You shout and wake everyone
Answer:
A thread pool manages a group of reusable threads to execute tasks. It improves performance
by reusing threads instead of creating new ones for each task.
✅ Code Example:
java
✅ Real-world Example:
Like a team of workers — instead of hiring every time, assign tasks to existing members.