JAVA - Interview Questions
1. What is the difference between JDK, JRE, and JVM?
Answer:
● JVM (Java Virtual Machine): Executes Java bytecode and provides a
platform-independent execution environment.
● 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
public class Hello {
public static void main(String[] args) {
System.out.println("Hello 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.
2. What are the main principles of Object-Oriented Programming?
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.
3. What is the difference between == and .equals() method?
Answer:
● == compares memory references, i.e., whether two object references point to the same
memory location.
● .equals() compares the actual content/data within the objects.
✅ Code Example:
java
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
✅ Real-world Example:
Two identical books: == checks if both are same physical book, .equals() checks if they
have same content.
4. Why is String immutable in Java?
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.
5. What is the difference between String, StringBuilder, and StringBuffer?
Answer:
● String: Immutable, each modification creates a new object.
● StringBuilder: Mutable, faster, not thread-safe.
● StringBuffer: Mutable and thread-safe, but slightly slower due to synchronization.
✅ Code Example:
Java
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Hello World
✅ Real-world Example:
● String is like a printed photo – permanent.
● StringBuilder is a whiteboard.
● StringBuffer is a whiteboard with a lock for safety in multi-person usage.
6. What is method overloading and method overriding?
Answer:
● Overloading: Defining multiple methods with the same name but different parameter
lists within the same class. It supports compile-time polymorphism.
● Overriding: Providing a specific implementation of a method already defined in a
superclass. It supports runtime 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.
7. What is the difference between abstract class and interface?
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
abstract class Animal {
abstract void makeSound();
}
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:
● private – Accessible only within the same class.
● (default) – Accessible within the same package.
● protected – Accessible within the same package and subclasses.
● public – Accessible from anywhere.
✅ Code Example:
java
public class Example {
private int a;
protected int b;
public int c;
}
✅ Real-world Example:
In a house:
● private is your bedroom
● protected is family hall
● public is living room
● default is like your neighbors only
9. What is the difference between static and non-static methods?
Answer:
● Static methods belong to the class and can be called without an object.
● Non-static methods belong to the instance and require an object to invoke.
✅ 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.
10. What is constructor chaining in Java?
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.
11. What is the difference between ArrayList and LinkedList?
Answer:
● ArrayList uses a dynamic array; supports fast random access but slow
insertion/deletion (except at the end).
● LinkedList uses a doubly-linked list; faster insertion/deletion but slower access by
index.
✅ Code Example:
java
List<String> arrList = new ArrayList<>();
List<String> linkList = new LinkedList<>();
✅ 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.
● Hashtable is synchronized, does not allow null keys or values.
● HashMap is preferred in single-threaded contexts due to better performance.
✅ Code Example:
java
Map<String, Integer> map1 = new HashMap<>();
Map<String, Integer> map2 = new Hashtable<>();
✅ 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.
13. How does HashMap work internally?
Answer:
HashMap stores data as key-value pairs using an array of buckets.
● Hashing is used to calculate index using hashCode().
● If a collision occurs, it stores entries in a linked list (or tree in Java 8+ for large
collisions).
● Retrieval uses equals() to find the exact key.
✅ Code Example:
java
Map<String, String> map = new HashMap<>();
map.put("name", "John"); // hashCode used to find bucket
✅ 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.
14. What is the difference between HashSet and TreeSet?
Answer:
● HashSet stores elements in no particular order, uses hashing.
● TreeSet stores elements in sorted order, uses a Red-Black Tree internally.
● TreeSet is slower due to sorting.
✅ Code Example:
java
Set<Integer> hSet = new HashSet<>();
Set<Integer> tSet = new TreeSet<>();
✅ Real-world Example:
● HashSet is like a basket where you throw items randomly.
● TreeSet is like a bookshelf where items are arranged alphabetically.
15. What is the Collections framework in Java?
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
List<String> names = new ArrayList<>();
Collections.sort(names);
✅ Real-world Example:
Think of the Collections framework as a toolbox containing different tools (List, Set, Map) for
different storage needs.
16. What is the difference between Iterator and ListIterator?
Answer:
● Iterator can traverse a collection only in forward direction.
● ListIterator can traverse both directions and modify elements (only for List).
● ListIterator is more powerful but only works with List implementations.
✅ Code Example:
java
List<String> list = new ArrayList<>();
Iterator<String> it = list.iterator();
ListIterator<String> lit = list.listIterator();
✅ 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:
● Comparable is used to define the natural ordering of objects. Class implements
compareTo().
● Comparator is used to define custom orderings, especially for sorting collections of
objects differently.
✅ Code Example:
java
class Student implements Comparable<Student> {
int marks;
public int compareTo(Student s) {
return this.marks - s.marks;
}
}
Comparator<Student> byName = (s1, s2) -> s1.name.compareTo(s2.name);
✅ Real-world Example:
● Comparable: Ranking students by roll number.
● Comparator: Sorting students by name or marks.
18. What happens when you add duplicate elements to a HashSet?
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
Set<String> set = new HashSet<>();
set.add("Java");
set.add("Java"); // ignored
System.out.println(set.size()); // 1
✅ Real-world Example:
A guest list app – if the same name is entered twice, only one entry is stored.
19. What is the difference between List and Set?
Answer:
● List allows duplicate elements and maintains insertion order.
● Set does not allow duplicates and may or may not maintain order (e.g., HashSet vs
TreeSet).
✅ Code Example:
java
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
✅ Real-world Example:
● List is like your shopping list – can have repeated items.
● Set is like your collection of stamps – only unique ones allowed.
20. What is the difference between Array and ArrayList?
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
int[] arr = new int[5];
ArrayList<Integer> list = new ArrayList<>();
✅ 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.
21. What is exception handling in Java?
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.
22. What is the difference between checked and unchecked exceptions?
Answer:
● Checked exceptions are checked at compile-time (e.g., IOException,
SQLException) and must be handled or declared.
● Unchecked exceptions occur at runtime (e.g., NullPointerException,
ArrayIndexOutOfBoundsException) and are not forced to be handled.
✅ Code Example:
java
// Checked
public void readFile() throws IOException {}
// Unchecked
int a = 10 / 0;
✅ Real-world Example:
● Checked: You must wear a helmet (rule).
● Unchecked: You might trip — it's up to you to prevent or recover.
23. What is the difference between throw and throws?
Answer:
● throw is used to explicitly throw an exception in the code.
● throws is used to declare exceptions a method might throw.
✅ Code Example:
java
void test() throws IOException {
throw new IOException("File not found");
}
✅ Real-world Example:
● throw: You throw the ball (raise exception).
● throws: You warn that you might throw it.
24. What is the finally block and when is it executed?
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.
26. What is the difference between final, finally, and finalize()?
Answer:
● final: Keyword to declare constants, prevent method overriding or inheritance.
● finally: Block that is always executed in exception handling.
● finalize(): Method called by garbage collector before object is destroyed.
✅ Code Example:
java
final int x = 10; // final variable
@Override
protected void finalize() throws Throwable {
System.out.println("Finalized");
}
✅ Real-world Example:
● final – sealed envelope
● finally – end routine
● finalize() – cleanup before deleting a file
27. What is multithreading in Java?
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
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
✅ 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.
● Implementing Runnable is more flexible and is preferred for creating threads.
✅ Code Example:
java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable running");
}
}
✅ Real-world Example:
● Thread: Full-time worker.
● Runnable: Freelancer you assign to a worker (thread) as a task.
29. What is synchronization in Java?
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
synchronized void printData() {
// critical section
}
✅ Real-world Example:
Like a bathroom lock — one person at a time to avoid conflicts.
30. What is the difference between wait() and sleep() methods?
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.
31. What is a deadlock and how can you avoid it?
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:
● Acquiring locks in a consistent order.
● Using tryLock() for timed lock attempts.
● Minimizing synchronized blocks.
✅ 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.
32. What is the volatile keyword in Java?
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
volatile boolean flag = true;
✅ 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.
● Heap is your bookshelf – larger, shared, long-term storage.
34. How does garbage collection work in Java?
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
List<String> original = new ArrayList<>();
List<String> shallow = original; // same reference
List<String> deep = new ArrayList<>(original); // new object
✅ 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.
36. What are wrapper classes in Java?
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:
● Autoboxing: Automatic conversion of a primitive to its wrapper object.
● Unboxing: Automatic conversion of a wrapper to its primitive type.
✅ 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
List<String> list = new ArrayList<>();
list.add("Java"); // Only Strings allowed
✅ 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
Runnable r = () -> System.out.println("Running");
✅ Real-world Example:
Like giving someone a sticky note with one instruction instead of typing a full letter.
40. What is the Stream API in Java 8?
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
List<String> names = Arrays.asList("Anna", "Bob", "Alice");
names.stream()
.filter(name -> name.startsWith("A"))
.forEach(System.out::println);
✅ 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();
}
Greet g = () -> System.out.println("Hi!");
✅ Real-world Example:
Like a remote with only one button – you can assign a specific action (lambda) to it.
42. What is Optional class in Java 8?
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
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Unknown"));
✅ 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
List<String> list = Arrays.asList("Java", "Python", "Go");
list.stream()
.filter(s -> s.startsWith("J"))
.forEach(System.out::println);
✅ Real-world Example:
A production conveyor belt where items go through multiple filters and are processed in
order.
44. What is method reference in Java 8?
Answer:
Method reference is a shorthand for calling methods using :: operator. It improves code
readability and is used with functional interfaces.
✅ Code Example:
java
List<String> names = Arrays.asList("Tom", "Jerry");
names.forEach(System.out::println); // Instead of lambda
✅ 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:
● Serialization is converting a Java object into a byte stream.
● Deserialization is converting the byte stream back into a Java object.
✅ Code Example:
java
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("data.ser"));
out.writeObject(obj); // Serialization
✅ Real-world Example:
Like saving a game and later loading it back with exact state restored.
46. What is the transient keyword in Java?
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
class User implements Serializable {
String name;
transient String password; // Not saved
}
✅ 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
Class<?> cls = Class.forName("java.lang.String");
Method[] methods = cls.getDeclaredMethods();
✅ Real-world Example:
Like a security camera that sees behind locked doors — lets you observe or manipulate
hidden parts.
48. What is the difference between composition and inheritance?
Answer:
● Inheritance is a “is-a” relationship where a class derives from another.
● Composition is a “has-a” relationship where a class contains references to other
objects.
✅ 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;
public void setName(String name) { this.name = name; }
public String getName() { return name; }
}
✅ Real-world Example:
Like a coffee machine — you don’t see the internals, you just press a button.
50. What is polymorphism and how is it implemented in Java?
Answer:
Polymorphism means "one name, many forms". In Java, it is implemented via:
● Method Overloading (Compile-time polymorphism)
● Method Overriding (Runtime polymorphism)
✅ 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.
51. What is the difference between static and instance variables?
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)
● Instance: Employee ID (unique to each person)
52. What is method hiding in Java?
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.
53. What is the difference between this and super keywords?
Answer:
● this refers to the current class instance.
● super refers to the immediate parent class instance.
✅ 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
● super: Refers to your parent
54. Can you override private methods in Java?
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.
55. What is constructor overloading?
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.
56. What happens if you don't provide a constructor in a class?
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:
● default: Accessible within the same package only.
● protected: Accessible within the same package and in subclasses outside the
package.
✅ Code Example:
java
protected int x; // accessible in subclasses
int y; // default access
✅ Real-world Example:
● default: Entry allowed for local members only
● protected: Also allows relatives (subclasses) from other places
58. What is the instanceof operator used for?
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?”
59. What is the difference between break and continue statements?
Answer:
● break exits the loop completely.
● continue skips current iteration and moves to the next.
✅ Code Example:
java
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
if (i == 4) break;
System.out.println(i);
}
✅ Real-world Example:
● break: You leave the room
● continue: You skip a person in a queue
60. What is the switch statement and how does it work?
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
int[] arr = {1, 2, 3};
// for loop
for (int i = 0; i < arr.length; i++) { }
// enhanced for loop
for (int val : arr) { }
✅ Real-world Example:
● for: Reading book page by page using numbers.
● for-each: Flipping through each page blindly without tracking numbers.
62. What is the difference between while and do-while loops?
Answer:
● while: Condition is checked before loop body is executed.
● do-while: Loop body is executed at least once, then condition is checked.
✅ Code Example:
java
int x = 5;
while (x < 5) { System.out.println("While"); }
do { System.out.println("Do-While"); } while (x < 5);
✅ Real-world Example:
● while: You check weather, then decide to go out.
● do-while: You go out once anyway, then check weather.
63. What are nested classes in Java?
Answer:
A nested class is a class defined within another class.
Types:
● Static nested class
● Non-static (inner) class
● 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:
● Static nested class doesn't need an outer class instance to be accessed.
● Inner class (non-static) needs an instance of the outer class.
✅ Code Example:
java
Outer.StaticNested sn = new Outer.StaticNested();
Outer.Inner in = new Outer().new Inner();
✅ Real-world Example:
● Static nested: Freelancer — works independently
● Inner class: Employee — needs a company (outer class)
65. What is an anonymous class in Java?
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
Runnable r = new Runnable() {
public void run() {
System.out.println("Running");
}
};
✅ 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:
● Local class: Named class defined inside a method.
● Anonymous class: No name, used for single-use, created at the point of use.
✅ 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.
68. What is the import statement and how does it work?
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.
69. What is the classpath in Java?
Answer:
Classpath is the path where the JVM looks for .class files when executing a program. It can
include directories, JAR files, etc.
✅ Code Example (Command Line):
bash
CopyEdit
java -cp myclasses/ MainClass
✅ Real-world Example:
Like a search folder location where Java looks to find the files it needs to run.
70. What is the main method and why is it static?
Answer:
The main method is the entry point for any Java application:
java
public static void main(String[] args)
It is static so it can be called by the JVM without creating an object.
✅ Real-world Example:
Like the main switch in a control panel — it must work even before anything else is turned on.
71. What is the difference between StringTokenizer and split() method?
Answer:
● StringTokenizer is a legacy class to break strings into tokens.
● split() is a modern method in String class that splits using regex.
✅ 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:
● Vector is synchronized and thread-safe, but slower.
● ArrayList is not synchronized, faster in single-threaded environments.
✅ Code Example:
java
List<String> list1 = new ArrayList<>();
List<String> list2 = new Vector<>();
✅ Real-world Example:
● Vector: Locked safe (slow, secure)
● ArrayList: Open drawer (fast, no locks)
73. What is the difference between Stack and Queue?
Answer:
● Stack follows LIFO (Last-In-First-Out).
● Queue follows FIFO (First-In-First-Out).
✅ Code Example:
java
Stack<Integer> stack = new Stack<>();
Queue<Integer> queue = new LinkedList<>();
✅ 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
Map<String, Integer> map = new LinkedHashMap<>();
✅ Use case:
When you want a map with predictable iteration order (like printing in the order of input).
75. What is WeakHashMap in Java?
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
Map<Object, String> map = new WeakHashMap<>();
Object key = new Object();
map.put(key, "value");
key = null; // GC may remove entry
✅ Real-world Example:
Like storing info on a whiteboard that gets erased when no one uses the marker again.
76. What is the difference between fail-fast and fail-safe iterators?
Answer:
● Fail-fast throws ConcurrentModificationException if collection is modified during
iteration (e.g., ArrayList, HashMap).
● Fail-safe allows modification without exception (e.g., ConcurrentHashMap).
✅ 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:
● Synchronized method locks the entire method.
● Synchronized block allows locking only a portion of code for fine-grained control.
✅ Code Example:
java
synchronized void fullLock() {}
void partialLock() {
synchronized(this) {
// only this part is locked
}
}
✅ Real-world Example:
● Method: Locking the entire building
● Block: Locking just one room
78. What is ThreadLocal class in Java?
Answer:
ThreadLocal provides thread-local variables. Each thread has its own independent copy of
the variable.
✅ Code Example:
java
ThreadLocal<Integer> tl = new ThreadLocal<>();
tl.set(100);
✅ Real-world Example:
Like personal notebooks — each person (thread) writes without interfering with others.
79. What is the difference between notify() and notifyAll()?
Answer:
● notify() wakes up one waiting thread.
● notifyAll() wakes up all waiting threads.
✅ 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
80. What is a thread pool in Java?
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
ExecutorService pool = Executors.newFixedThreadPool(5);
pool.execute(() -> System.out.println("Running"));
✅ Real-world Example:
Like a team of workers — instead of hiring every time, assign tasks to existing members.