Basic Java Interview Questions (1-10)
These foundational questions test core Java concepts suitable for freshers and beginners.
1. What is Java and why is it platform-independent?
Java is a high-level, object-oriented programming language. It is platform-independent because Java code is compiled into bytecode, which runs on any device with a Java Virtual Machine (JVM).[1][2]
2. What is the difference between JDK, JRE, and JVM?
JDK (Java Development Kit) is for development, JRE (Java Runtime Environment) is for running Java programs, and JVM (Java Virtual Machine) executes the bytecode.[2]
3. Explain the difference between == and equals() in Java.
== compares references (memory addresses), while equals() compares values. For strings, equals() checks content equality.[6]
4. What is the purpose of the main() method in Java?
The main() method is the entry point of any Java application with signature public static void main(String[] args).[6]
5. What are the access specifiers in Java?
Access specifiers are public, private, protected, and default (no modifier). They control visibility of classes, methods, and variables.[7]
6. Explain String, StringBuilder, and StringBuffer in Java.
String is immutable, StringBuilder is mutable and not thread-safe, StringBuffer is mutable and thread-safe.[4]
7. What is a try-catch-finally block?
try contains code that might throw an exception, catch handles it, and finally executes cleanup code regardless.[4]
8. What is the difference between ArrayList and LinkedList?
ArrayList uses a dynamic array (fast random access), LinkedList uses a doubly-linked list (fast insertions/deletions).[5]
9. How do you reverse a string in Java?
Use StringBuilder’s reverse() method or a loop with StringBuffer.
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // olleh
}
}
[1]
10. What is the difference between method overloading and overriding?
Overloading is multiple methods with same name but different parameters in same class. Overriding is redefining a superclass method in subclass.[5]
Intermediate Java Interview Questions (11-20)
These questions assess practical knowledge for candidates with 1-3 years of experience.
11. What is the Collections Framework in Java?
The Collections Framework provides interfaces and classes like List, Set, Map for storing and manipulating groups of objects.[5]
12. Explain Comparable vs Comparator.
Comparable has compareTo() for natural ordering. Comparator has compare() for custom ordering.[2]
13. What are Lambda Expressions in Java 8?
Lambdas enable functional programming, like (a, b) -> a + b, for concise code with functional interfaces.[1][3]
14. How do Streams work in Java?
Streams process collections functionally: list.stream().filter(n -> n > 5).forEach(System.out::println).[3]
15. What is the difference between HashMap and ConcurrentHashMap?
HashMap is not thread-safe. ConcurrentHashMap allows concurrent reads/writes with thread safety.[1]
16. Explain Exception Handling hierarchy in Java.
Throwable is root, with Error and Exception. RuntimeException is unchecked; others are checked.[4]
17. How do you swap two numbers without a temporary variable?
Use arithmetic: a = a + b; b = a – b; a = a – b;
int a = 10, b = 20;
a = a + b; // 30
b = a - b; // 10
a = a - b; // 20
[1]
18. What is an Enum in Java?
Enum is a special class for fixed constants, like enum Day {MONDAY, TUESDAY};[2]
19. Explain the difference between shallow copy and deep copy.
Shallow copy copies references; deep copy copies objects recursively.[7]
20. How do you check if two strings are anagrams?
Sort both strings and compare, or count character frequencies.
boolean isAnagram(String s1, String s2) {
int[] count = new int[26];
for (char c : s1.toLowerCase().toCharArray()) count[c - 'a']++;
for (char c : s2.toLowerCase().toCharArray()) count[c - 'a']--;
for (int i : count) if (i != 0) return false;
return true;
}
[7]
Advanced Java Interview Questions (21-30)
These scenario-based and complex questions target 3-6 years experienced developers, often from companies like Atlassian, Adobe, or Zoho.
21. How does Garbage Collection work in Java?
JVM automatically frees memory by marking unreachable objects. Generations: Young (Eden, Survivor), Old.[3]
22. What is a Singleton pattern and how to make it thread-safe?
Singleton ensures one instance. Thread-safe with synchronized getInstance() or enum.
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}
[1]
23. Explain deadlock and how to avoid it.
Deadlock occurs when threads wait cyclically for locks. Avoid by consistent lock ordering, timeouts.[1]
24. What is the Producer-Consumer problem? Implement using wait/notify.
Producers add to queue, consumers remove. Use synchronized with wait() and notify().
class Queue {
private int item;
private boolean full = false;
public synchronized void produce(int n) throws InterruptedException {
while (full) wait();
item = n; full = true; notify();
}
public synchronized int consume() throws InterruptedException {
while (!full) wait();
full = false; notify(); return item;
}
}
[1]
25. How does ExecutorService improve multithreading?
ExecutorService manages thread pools for task execution, reusing threads.
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Task"));
executor.shutdown();
[1]
26. What are Atomic variables and their use?
AtomicInteger etc. provide thread-safe operations without locks, using CAS (Compare-And-Swap).[1]
27. Explain CompletableFuture for asynchronous programming.
CompletableFuture handles async tasks: CompletableFuture.supplyAsync(() -> “result”).thenApply(s -> s.length());[1]
28. What is Reflection in Java?
Reflection allows runtime inspection/modification of classes, fields, methods via Class.forName().[2]
29. Scenario: Implement a thread-safe cache using ConcurrentHashMap at Paytm.
Use ConcurrentHashMap with computeIfAbsent for atomic get-or-put.
ConcurrentHashMap cache = new ConcurrentHashMap<>();
Object value = cache.computeIfAbsent("key", k -> expensiveOperation());
[1]
30. Scenario: Debug a memory leak in a Salesforce Java application.
Use VisualVM/JFR to profile heap. Check static references, unclosed resources, improper caching.[3]