- 120 Java language questions with compiler-style samples on a clean URL.
- DSA, coding process, company OA, and aptitude are split into dedicated hubs.
- Most repeated: HashMap internals, equals/hashCode, wait vs sleep, streams.
- Type reverse, palindrome, duplicates, and two-sum from memory.
- Planning salary: Java freshers roughly Rs.3.5-6 LPA - not guaranteed.
Related Interview Question Hubs
DSA and coding stay on separate pages on purpose. Use the matching hub:
- DSA Interview Questions and Answers
- Coding Interview Questions and Answers
- Programming Problems and Solutions
- Company-wise Coding Questions
- Aptitude Questions and Answers
- Logical Reasoning Questions and Answers
- Quantitative Aptitude Questions and Answers
- Python, JavaScript, React, Java
Java interview questions and answers in 2026 still split across core fundamentals, OOP design, strings and memory, collections, exceptions, multithreading, modern Java 8-21 features, JVM internals, and live coding - but fresher panels in Chennai now probe deeper than a quick 50-question skim. This is the 120-question deep guide (not the shorter list at Java interview questions and answers), written so each answer opens with a direct response you can speak in under a minute.
Last updated: September 9, 2026 - Reviewed by Asmorix Java mentors in Chennai
Asmorix mentors compiled these from TCS/Infosys services drives, banking captives, and product/GCC screens across OMR and Guindy. Pair this page with Java training in Chennai, inheritance in Java, strings in Java, Object class methods in Java, IT salary in India for freshers, full stack developer course in Chennai, and more on the Asmorix blog.
How Java Interviews Are Structured in India (2026)
Most Java fresher and 0-3 year loops in Chennai follow four rounds. Know the filter before you memorize 120 answers:
| Round | What is tested | Typical filter |
|---|---|---|
| Online assessment (OA) | Aptitude, logical reasoning, 1-2 easy Java coding problems | Compiling code with correct edge cases beats clever but broken logic |
| Technical round 1 | Core Java, OOP, strings, collections basics, small programs | Direct one-line answer plus one concrete example |
| Technical round 2 | Exceptions, multithreading, Java 8+, JVM, project deep-dive | Can you explain WHY the JVM or API behaves that way |
| Managerial / HR | Communication, relocation, salary fit, notice period | Structured, honest answers without overselling |
Key takeaway: interviewers reward a crisp first sentence, then a short example - exactly how every answer below is structured for answer-engine and spoken delivery.
Core Java Interview Questions and Answers (Q1-Q20)
1. What is Java and why is it called Write Once, Run Anywhere (WORA)?
Java is a class-based language whose compiler produces platform-neutral bytecode that any compliant JVM can execute. WORA works because you ship .class files, not native machine code - the JVM on Windows, Linux, or macOS translates bytecode to local instructions at runtime. Interviewers follow up: WORA assumes a compatible JVM exists on the target machine; it is not magic without one. In Chennai services drives, tie this to deployment on Linux servers while developers code on Windows laptops.
2. What is the difference between JDK, JRE, and JVM?
The JVM executes bytecode; the JRE is the JVM plus core runtime libraries needed to run Java programs; the JDK is the JRE plus developer tools like javac, jar, and debuggers. Say it as: JDK for building, JRE for running, JVM as the engine inside both. Captive banking panels sometimes ask which you install on a CI server - answer JDK if you compile there, JRE if you only run packaged jars.
3. What is the JIT compiler in Java?
The Just-In-Time (JIT) compiler inside the JVM converts hot bytecode methods into native machine code after profiling, so repeated execution runs faster than pure interpretation. Cold code stays interpreted; frequently called methods get optimized in the background. Follow-up: JIT is why micro-benchmarks that run once lie - warm up loops before measuring. Product interviewers in Bengaluru-style GCCs love this JVM detail after basic JDK questions.
4. Is Java a 100% object-oriented language?
No - Java is not purely object-oriented because it has primitive types (int, double, etc.) that are not objects and can be used without wrapping. Everything else lives in classes, but primitives break the "everything is an object" rule. Mention autoboxing bridges the gap for collections, yet primitives still sit outside the object model. Saying "mostly OOP with primitives as an exception" sounds more honest than claiming purity.
5. Why must the main method be public static void main(String[] args)?
It is public so the JVM launcher can invoke it from outside the class, static so no object is required before entry, and void because exit status is handled via System.exit(), not a return value. The String[] args array carries command-line tokens. Variations like public static void main(String... args) are valid; changing access or return type breaks startup.
6. What is the difference between primitive types and reference types?
Primitives store the actual value directly in the stack frame (for local variables) with fixed sizes, while reference types store a heap address pointing to an object. Primitives default to zero/false; references default to null. Follow-up: assigning a reference copies the address, not the object - two variables can point to the same heap instance. This distinction drives answers on pass-by-value later in the same interview.
7. What are default values for instance and local variables?
Instance and static fields get JVM defaults: numeric types become 0, boolean becomes false, and references become null. Local variables inside methods have no default - the compiler rejects use before assignment. Interviewers trap candidates who assume locals start at zero; always initialize locals explicitly in coding rounds.
8. Explain implicit vs explicit casting in Java.
Implicit (widening) casting happens automatically when a smaller numeric type fits safely into a larger one, like int to long. Explicit (narrowing) casting requires parentheses when going larger to smaller, like (int) 3.14, and may lose precision. Follow-up: reference casting uses the same syntax but needs an instanceof check to avoid ClassCastException at runtime.
9. What is var in Java and where can you use it?
var (since Java 10) lets the compiler infer a local variable's type from its initializer - it is not dynamic typing. You can use it only for locals with an initializer, not for fields, parameters, or methods without immediate assignment. Example: var list = new ArrayList<String>(); infers ArrayList<String>. Chennai panels accept it in modern code but still expect you to read inferred types aloud.
10. What is stored on the stack vs the heap in Java?
Each thread gets a stack holding method frames, local primitives, and reference addresses; the heap holds all objects and arrays shared across threads. When a method returns, its stack frame is popped; heap objects survive until garbage collection clears unreachable instances. Follow-up: two locals can reference the same heap object - mutating through one reference is visible through the other.
11. What is a classloader and why does Java use one?
A classloader loads .class bytecode into the JVM method area on demand using a delegation model - bootstrap, platform, and application loaders. Lazy loading keeps startup fast and enables modular deployments like Spring Boot fat jars. Interviewers ask about ClassNotFoundException vs NoClassDefFoundError as a follow-up - classloader failures cause the former at load time.
12. What is Java bytecode?
Bytecode is the intermediate instruction set produced by javac and executed by the JVM - neither source nor native machine code. It enables portability because each platform's JVM interprets or JIT-compiles the same .class files. You can inspect it with javap -c MyClass when debugging verifier or performance questions. Services interviewers rarely go this deep unless the role mentions performance tuning.
13. Why does Java use packages?
Packages group related classes into namespaces, prevent naming collisions, and control visibility through access modifiers plus import statements. The folder structure must mirror the package name: com.asmorix.demo.App lives under com/asmorix/demo/App.java. Follow-up: default (package-private) members are visible only within the same package - a common trick question in core Java round one.
14. Explain the four access modifiers in Java.
private is class-only, default (no keyword) is package-wide, protected adds subclass access outside the package, and public is everywhere. Choose the narrowest modifier that still satisfies the API - interviewers link this to encapsulation and API design. Banking captives often ask for a quick table drawn on paper; practice writing it cleanly.
15. What does the static keyword mean in Java?
static members belong to the class, not any single instance - one shared copy exists for all objects. Static methods cannot use this or access instance fields directly without an object reference. Common examples: main(), utility helpers like Math.max(), and factory methods. Overusing static state is a code smell interviewers probe when discussing testability.
16. What does the final keyword do in Java?
final on a variable prevents reassignment, on a method blocks overriding, and on a class blocks extension (like String). A final reference cannot point to another object, but the object itself may still mutate unless immutable. Follow-up: blank final instance fields must be assigned in every constructor - a subtle compiler rule worth mentioning.
17. What is the difference between finally and finalize()?
finally is a try/catch block that always runs cleanup code except on System.exit() or JVM crash, while finalize() was a deprecated Object hook invoked by GC before reclaiming an object. Modern code uses try-with-resources instead of relying on finalize(), which was removed in Java 18+. Say clearly: never depend on finalize() for resource cleanup.
18. What is the difference between this and super?
this refers to the current object instance for field disambiguation and constructor chaining with this(); super refers to the immediate parent for calling super() constructors or overridden methods. Both must be the first statement when used in constructors. Neither works inside static methods because there is no current instance.
19. What is the difference between a constructor and a method?
A constructor shares the class name, has no return type, and runs once when new creates an object to initialize state. Methods have return types (or void) and can be called any number of times after the object exists. If you omit constructors, the compiler supplies a default no-arg unless another constructor is written.
20. Can a top-level Java class be private or protected?
No - a top-level class may only be public or package-private (default); private and protected apply to nested classes only. A public class name must match its filename exactly. This rule trips freshers who try to hide utility classes - use package-private or nest them instead.
Java OOP Interview Questions and Answers (Q21-Q35)
21. What are the four pillars of OOP in Java?
They are encapsulation (hide state, expose behavior), inheritance (reuse via extends), polymorphism (one interface, many forms through overloading and overriding), and abstraction (show essentials, hide complexity via abstract classes and interfaces). Give one sentence plus one mini example each - interviewers punish definition-only answers. See also inheritance in Java for deeper examples.
22. What is the difference between a class and an object?
A class is the blueprint defining fields and methods; an object is a runtime instance with its own heap state created via new. One class can spawn many objects: Employee e1 = new Employee(); allocates distinct memory. Follow-up: classes live in the method area; objects live on the heap until collected.
23. What is method overloading vs method overriding?
Overloading is same method name with different parameter lists in one class, resolved at compile time. Overriding is a subclass replacing a superclass method with the same signature, resolved at runtime via dynamic dispatch. Say "compile-time vs runtime polymorphism" to close the answer cleanly. Return type alone cannot distinguish overloads.
24. What is a covariant return type in Java?
An overriding method may return a subtype of the parent method's return type since Java 5 - for example, a clone() override returning a specific class instead of Object. The parameter list and access modifier rules still apply; you cannot override with weaker access. It appears rarely in fresher code but shows up in framework API questions.
25. When do you choose an abstract class over an interface?
Pick an abstract class when subclasses share state, constructors, or partial implementation; pick an interface for capability contracts multiple unrelated classes can implement. Since Java 8, interfaces may have default and static methods, but they still cannot hold instance fields. A class extends one abstract class yet can implement many interfaces.
26. Why does Java avoid multiple class inheritance?
Java allows single inheritance of classes to prevent the diamond problem - two parents supplying conflicting method bodies. Multiple inheritance of type is still possible through interfaces, with explicit resolution if two defaults clash. Follow-up: the subclass must override and can delegate with InterfaceName.super.method().
27. Explain encapsulation with a BankAccount example.
Encapsulation hides internal state behind controlled methods - a BankAccount keeps balance private and exposes deposit() and withdraw() that validate amounts so outside code cannot set negative balances directly.
class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
public double getBalance() { return balance; }
}
Banking captives in Chennai love this pattern because it ties OOP to real validation rules they expect in production services.
28. Composition vs inheritance - which should you prefer?
Prefer composition (has-a) when behavior can be swapped or combined without fragile parent-child coupling; use inheritance (is-a) when the subclass truly is a specialized version of the parent. Composition follows the "favor composition over inheritance" guideline from effective Java style interviews. Example: a Car has an Engine, it is not an Engine.
29. What types of constructors exist in Java?
Default (compiler-generated no-arg when none written), no-arg (explicit empty constructor), and parameterized constructors that accept values to initialize fields. Constructors can be overloaded and chained with this() or super() as the first statement. Private constructors support singleton or utility-class patterns.
30. How does constructor chaining work with this() and super()?
this() calls another constructor in the same class; super() calls a parent constructor - both must be the first statement in the constructor body. The chain eventually reaches Object(). If you omit super(), the compiler inserts a call to the parent no-arg constructor automatically.
31. Name key methods of java.lang.Object.
Every class inherits equals(), hashCode(), toString(), getClass(), clone(), finalize() (removed), and wait/notify methods. Override equals and hashCode together when instances define logical equality - see Object class methods in Java for detail. Default equals uses reference identity like ==.
32. What does the instanceof operator do?
instanceof returns true if an object is an instance of a type or its subclass, or implements an interface - false for null. Since Java 16, pattern matching lets you write if (obj instanceof String s) to bind and cast in one step. Use it before downcasting to avoid ClassCastException.
33. What are coupling and cohesion?
Coupling measures how dependent modules are on each other - lower is better; cohesion measures how focused a class is on one job - higher is better. Tight coupling across layers makes testing painful; low cohesion "god classes" confuse reviewers. Interviewers accept one sentence each plus a Spring Boot layering example (controller vs service).
34. Give a one-line summary of SOLID principles.
Single responsibility (one reason to change), Open/closed (extend without modifying), Liskov substitution (subtypes must honor contracts), Interface segregation (small focused interfaces), Dependency inversion (depend on abstractions). You rarely recite all five in fresher rounds, but naming two with examples shows maturity product teams notice.
35. What is a marker interface in Java?
A marker interface has no methods and tags a class for framework processing - classic examples include Serializable and Cloneable. Modern Java favors annotations over empty interfaces, but interviewers still ask because legacy APIs use markers extensively. Mention that marking alone does nothing unless runtime code checks the type.
Java String and Memory Interview Questions (Q36-Q48)
36. Why are Strings immutable in Java?
String objects cannot change after creation - any "modification" creates a new instance. Immutability enables the string pool, thread safety without locks, stable hashCode() for hash maps, and safer handling of credentials in memory. Follow-up: char arrays can be cleared; immutable Strings reduce accidental leakage but stay in the pool until collected. Deep dive: strings in Java.
37. What is the difference between == and equals()?
== compares references (same heap address), while equals() compares logical content when overridden - String overrides equals to compare characters.
public class EqualsDemo {
public static void main(String[] args) {
String a = new String("java");
String b = new String("java");
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
false
true
38. What is the String constant pool?
The string pool (intern pool) stores literal strings in a special heap region so repeated literals share one object - String s = "hello"; may reuse an existing "hello". Literals created at compile time enter the pool; new String("hello") always creates a heap object outside the pool unless you call intern().
39. String vs StringBuilder vs StringBuffer - when to use each?
Use String for fixed text, StringBuilder for heavy concatenation in a single thread (not synchronized, faster), and StringBuffer when multiple threads mutate the same buffer (synchronized, slightly slower). In loops, StringBuilder avoids O(n^2) object creation from repeated String concatenation.
40. What does String.intern() do?
intern() returns the pooled canonical copy of a string, adding it to the pool if missing. It saves memory when many duplicate strings exist but can grow the pool unexpectedly in high-throughput apps. Modern code often avoids manual interning unless profiling shows duplicate string pressure.
41. What is the difference between new String("x") and String s = "x";?
The literal form may reuse a pooled instance; new String("x") always allocates a fresh heap object even if "x" already exists in the pool. Comparing with == therefore differs; always use equals() for content. Interviewers expect you to draw two boxes on paper for this one.
42. How does String.substring() behave in modern Java?
Since Java 7u6, substring creates a new char array copy instead of sharing the parent backing array - avoiding memory leaks from huge originals pinned by tiny substrings. It still returns a new String object; immutability is unchanged. Mention this when seniors ask "does substring share memory?"
43. Why is String not a primitive type?
String is a final class wrapping a char array with rich API methods - primitives cannot carry behavior or participate in generics/collections without wrappers. Treating text as an object lets the JVM optimize via the pool and lets developers override usage patterns consistently. It is reference type stored on the heap like any other object.
44. Why is the String class declared final?
Final prevents subclassing that could break immutability or security assumptions - imagine a malicious String subclass changing after being used as a map key. It also lets the JVM apply aggressive optimizations knowing no subclass overrides behavior. Same reasoning applies to wrapper caches and system classes.
45. What are wrapper classes and autoboxing?
Wrappers like Integer box primitives into objects for collections and generics; autoboxing converts automatically (int to Integer) and unboxing reverses it. Unboxing null throws NullPointerException - a classic runtime trap in coding tests.
import java.util.*;
public class AutoboxingNpe {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>();
scores.add(85);
scores.add(null);
int total = 0;
for (Integer s : scores) {
total += s;
}
}
}
Exception in thread "main" java.lang.NullPointerException
46. What is the Integer cache (-128 to 127)?
Java caches Integer objects for values -128 through 127, so autoboxed literals in that range may share instances - Integer a = 127; Integer b = 127; can make a == b true, but 128 fails.
public class IntegerCacheDemo {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer x = 128, y = 128;
System.out.println(a == b);
System.out.println(x == y);
}
}
true
false
47. Does Java pass by reference or pass by value?
Java is always pass-by-value: for primitives the value is copied; for objects the reference value (address) is copied, not the object itself. Reassigning a parameter inside a method does not change the caller's variable. Mutating the object through the shared reference is visible to the caller - that distinction confuses many candidates.
class Box { int v; Box(int v) { this.v = v; } }
public class PassByValueDemo {
static void bump(Box b) { b.v = 99; }
static void swapRef(Box a, Box b) { Box t = a; a = b; b = t; }
public static void main(String[] args) {
Box box = new Box(1);
bump(box);
System.out.println(box.v);
Box x = new Box(2), y = new Box(3);
swapRef(x, y);
System.out.println(x.v + " " + y.v);
}
}
99
2 3
48. What is shallow copy vs deep copy?
Shallow copy duplicates the top-level object but shares nested references; deep copy recursively clones nested objects so changes in one graph do not leak to another. Object.clone() default is shallow; deep copies need manual logic or libraries. Collections questions often follow when copying lists of mutable objects.
Java Collections Interview Questions and Answers (Q49-Q65)
49. Explain the Java Collections Framework hierarchy.
Collection branches into List, Set, and Queue; Map is a separate hierarchy for key-value pairs. Implementations include ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap. Lists allow duplicates with order; Sets reject duplicates; Maps index by unique keys.
50. ArrayList vs LinkedList - when do you pick each?
ArrayList uses a dynamic array: fast random access, slower middle inserts due to shifting. LinkedList uses nodes: fast head/tail ops, slow indexed access. Real workloads favor ArrayList for cache locality - say that aloud in Chennai services interviews instead of quoting Big-O only.
51. What is Vector and why is it rarely used now?
Vector is a legacy synchronized resizable array - every method is synchronized, making it slower than ArrayList for single-threaded code. Use ArrayList by default or Collections.synchronizedList / concurrent collections when thread safety matters. Mentioning Vector shows you know history without recommending it.
52. How does HashMap work internally in Java?
HashMap stores nodes in an array of buckets; hashCode() picks the bucket and equals() resolves collisions inside the bucket. Since Java 8, linked lists treeify to red-black trees after 8 nodes in one bucket for O(log n) worst case.
import java.util.*;
public class HashMapDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("java", 21);
map.put("spring", 6);
System.out.println(map.get("java"));
System.out.println(map.containsKey("go"));
}
}
21
false
53. What is the treeify threshold of 8 in HashMap?
When a single bucket's linked list grows beyond 8 entries (and the table is at least 64 buckets), Java converts that bucket's list into a red-black tree to keep lookup efficient under hash collisions. If size drops below 6, it untreeifies back to a list. This detail separates memorizers from candidates who read JDK source notes.
54. What is HashMap load factor 0.75?
Default load factor 0.75 means HashMap resizes when size exceeds 75% of capacity, doubling buckets and rehashing entries. It balances memory vs collision rate - higher load factor saves space but slows lookups. Initial capacity 16 is also default unless you specify otherwise in the constructor.
55. What is the equals() and hashCode() contract?
If two objects are equal by equals(), they must share the same hashCode(); unequal objects may collide. Breaking the contract makes HashMap/HashSet lose entries mysteriously. Always override both together using IDE generation or Objects.hash().
56. HashMap vs Hashtable vs ConcurrentHashMap?
HashMap is unsynchronized and allows one null key; Hashtable is legacy synchronized-on-every-call and obsolete; ConcurrentHashMap locks at bucket level for scalable concurrent reads/writes without blocking the entire map. Default to HashMap single-threaded, CHM in multi-threaded services.
57. HashSet vs TreeSet vs LinkedHashSet?
HashSet offers O(1) unordered uniqueness; LinkedHashSet keeps insertion order with small overhead; TreeSet keeps sorted order via red-black tree with O(log n) ops and navigable methods like headSet. Pick based on ordering needs, not habit.
58. HashMap vs TreeMap vs LinkedHashMap?
HashMap is general-purpose unordered; TreeMap sorts by key (natural or Comparator); LinkedHashMap maintains insertion or access order useful for LRU caches. TreeMap allows null keys only if comparator permits; HashMap allows one null key.
59. Comparable vs Comparator - what is the difference?
Comparable defines natural order inside the class via compareTo; Comparator is external via compare, often as a lambda for multiple sort orders.
import java.util.*;
record Employee(String name, int salary) {}
public class ComparatorDemo {
public static void main(String[] args) {
List<Employee> list = List.of(
new Employee("Anu", 60000), new Employee("Bala", 45000));
list = new ArrayList<>(list);
list.sort(Comparator.comparingInt(Employee::salary));
System.out.println(list.get(0).name());
}
}
Bala
60. What are fail-fast vs fail-safe iterators?
Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException on structural change during iteration via modCount checks. Fail-safe iterators (ConcurrentHashMap, CopyOnWriteArrayList) work on snapshots or concurrent structures and never throw, but may miss latest updates.
61. Iterator vs ListIterator?
Iterator traverses forward only and works on any Collection; ListIterator traverses lists bidirectionally and supports set, add, and index-aware navigation. Use ListIterator when you need reverse iteration or in-place replacement while looping.
62. Array vs ArrayList - key differences?
Arrays are fixed-length with primitive or reference elements and can hold primitives directly; ArrayList is resizable, object-only (via wrappers for primitives), and implements Collection APIs. Arrays use length field; ArrayList uses size() method. Varargs and generics favor ArrayList in modern APIs.
63. What is PriorityQueue?
PriorityQueue is an unbounded heap-based queue where the head is the least element per natural ordering or a supplied Comparator - not FIFO. Insert/remove are O(log n). Useful for scheduling tasks or finding top-k elements when paired with limited size.
64. How does ConcurrentHashMap achieve concurrency?
Modern CHM uses node arrays with synchronized bin heads and CAS operations instead of locking the whole map; older docs mention segments but Java 8+ refined to finer locking. Reads rarely block; writes lock only affected bins. Expect follow-ups comparing to Collections.synchronizedMap.
65. What are WeakHashMap and synchronizing a HashMap?
WeakHashMap holds weak keys eligible for GC when no strong references remain - handy for caches keyed by transient objects. To synchronize HashMap, wrap with Collections.synchronizedMap(new HashMap<>()) or prefer ConcurrentHashMap for better throughput under contention.
Java Exception Handling Interview Questions (Q66-Q73)
66. Explain checked vs unchecked exceptions.
Checked exceptions (subclasses of Exception except RuntimeException) must be declared or caught at compile time - IO, SQL. Unchecked exceptions extend RuntimeException and signal programming bugs like NPE - no compile-time enforcement.
67. What is the difference between throw and throws?
throw instantiates and raises an exception inside a method body; throws declares checked exceptions the method may propagate to callers. One executes; the other documents. Example: throw new IllegalArgumentException("bad"); vs void read() throws IOException.
68. What is try-with-resources?
Try-with-resources (Java 7+) auto-closes resources implementing AutoCloseable in reverse order, even when exceptions occur - replacing manual finally blocks.
import java.io.*;
public class TryWithResourcesDemo {
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(
new StringReader("asmorix"))) {
System.out.println(br.readLine());
}
}
}
asmorix
69. When does finally NOT run?
Finally runs after try/catch except when the JVM exits via System.exit(), the process is killed, or the thread is halted abruptly. Returning from try still triggers finally unless exit is called first. Mention that returning from finally can override try return values - a smell.
70. How do you create a custom exception?
Extend Exception for checked or RuntimeException for unchecked, provide constructors calling super(message), and throw when domain rules fail - like insufficient balance in payments code.
71. Why must catch blocks order from specific to general?
The compiler matches the first compatible catch; placing Exception before IOException makes the specific block unreachable. Always catch subclasses before superclasses. Same rule applies to multi-catch with unrelated types combined carefully.
72. Error vs Exception - should you catch Error?
Error (OutOfMemoryError, StackOverflowError) signals serious JVM problems you generally do not catch; Exception represents recoverable conditions. Catching Error hides fatal states and is discouraged except in isolated framework boundaries.
73. What are suppressed exceptions in try-with-resources?
When try and close both throw, the primary exception is thrown and close exceptions are added as suppressed via addSuppressed. Inspect them with getSuppressed() during debugging. This behavior is why try-with-resources beats silent finally swallowing.
Java Multithreading Interview Questions (Q74-Q88)
74. What are the ways to create a thread in Java?
Extend Thread and override run, implement Runnable (preferred), or submit Callable to an ExecutorService when you need results. In 2026 also cite virtual threads: Thread.startVirtualThread(task) on Java 21.
75. Explain Java thread lifecycle states.
States: NEW, RUNNABLE, BLOCKED (waiting for monitor), WAITING (wait/join no timeout), TIMED_WAITING (sleep/timed wait), TERMINATED. You cannot restart a terminated thread - second start() throws IllegalThreadStateException.
76. What does synchronized do?
It ensures mutual exclusion on the intrinsic lock of an object - instance methods lock this, static methods lock the Class object - providing visibility of writes after release. It does not replace good design; over-synchronization causes contention.
public class SynchronizedCounter {
private int count = 0;
synchronized void increment() { count++; }
synchronized int getCount() { return count; }
public static void main(String[] args) throws Exception {
SynchronizedCounter c = new SynchronizedCounter();
Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.increment(); });
t1.start(); t2.start(); t1.join(); t2.join();
System.out.println(c.getCount());
}
}
2000
77. What is volatile?
volatile guarantees visibility of reads/writes across threads without caching per thread, but does not make compound actions like count++ atomic. Use AtomicInteger or synchronized for increments; volatile suits simple flags.
78. Compare wait(), sleep(), yield(), and join().
wait() releases the monitor and waits for notification; sleep() pauses without releasing locks; yield() hints the scheduler to let peers run; join() waits for another thread to finish.
public class WaitSleepDemo {
static final Object lock = new Object();
public static void main(String[] args) throws Exception {
Thread t = new Thread(() -> {
synchronized (lock) {
try { lock.wait(50); } catch (InterruptedException e) {}
System.out.println("worker done");
}
});
t.start();
Thread.sleep(100);
System.out.println("main done");
}
}
worker done
main done
79. notify() vs notifyAll()?
notify() wakes one arbitrary waiting thread on the monitor; notifyAll() wakes all waiters, who must recompete for the lock. Prefer notifyAll when conditions may apply to multiple threads to avoid lost signals.
80. What is deadlock and how do you prevent it?
Deadlock is circular lock waiting - thread A holds L1 wants L2 while B holds L2 wants L1. Prevent by consistent lock ordering, tryLock with timeouts, or reducing lock scope. jstack reports "Found one Java-level deadlock" in production triage.
81. Livelock vs starvation?
Livelock is threads actively responding to each other without progress (polite collision avoidance); starvation is a thread never gaining CPU or locks due to priority or scheduling. Both differ from deadlock where threads are blocked waiting.
82. What is ExecutorService?
ExecutorService manages a thread pool, decoupling task submission from thread lifecycle - submit Runnable/Callable, reuse workers, cap concurrency, shutdown gracefully with shutdown() and await termination.
83. Callable vs Runnable?
Runnable runs void tasks and cannot throw checked exceptions to callers; Callable returns a value and may throw checked exceptions, consumed via Future. Use Callable when the task produces a result or needs declared exceptions.
84. Future vs CompletableFuture?
Future represents a pending result from async work with blocking get(); CompletableFuture composes async pipelines with thenApply, thenCombine, and non-blocking callbacks. Modern services code favors CompletableFuture or reactive stacks built on it.
85. What is AtomicInteger?
AtomicInteger provides lock-free thread-safe increments and CAS operations on an int wrapper - preferable to synchronized counters under contention. Methods like incrementAndGet are atomic; volatile alone is insufficient for ++.
86. What is ThreadLocal?
ThreadLocal gives each thread its own copy of a variable - common for SimpleDateFormat before Java 8 date/time or user context in web requests. Always remove values in pooled threads to avoid leaks in app servers.
87. What are virtual threads in Java 21?
Virtual threads are lightweight JVM-managed threads cheap enough to run millions blocking on IO - created via Thread.ofVirtual() or startVirtualThread.
public class VirtualThreadDemo {
public static void main(String[] args) throws Exception {
Thread vt = Thread.startVirtualThread(() ->
System.out.println("virtual: " + Thread.currentThread()));
vt.join();
}
}
virtual: VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1
88. What is pinning and structured concurrency?
Pinning happens when a virtual thread blocks on a synchronized block or native code, tying it to a carrier platform thread - reducing scalability. Structured concurrency (preview APIs) scopes subtasks to parent lifetimes so failures cancel siblings cleanly. Mention both when GCC interviewers ask about Java 21 adoption blockers.
Modern Java 8 to 21 Interview Questions (Q89-Q101)
89. What are lambda expressions?
Lambdas are concise anonymous functions implementing functional interfaces: (a, b) -> a + b replaces verbose inner classes. They power streams and event handlers; parameter types are inferred when unambiguous.
import java.util.function.*;
public class LambdaDemo {
public static void main(String[] args) {
BinaryOperator<Integer> add = (a, b) -> a + b;
Predicate<String> longWord = s -> s.length() > 4;
System.out.println(add.apply(10, 5));
System.out.println(longWord.test("java"));
}
}
15
false
90. What is a functional interface?
An interface with exactly one abstract method, optionally annotated @FunctionalInterface - examples: Predicate, Function, Consumer, Supplier, Runnable. Compiler enforces the single abstract method rule.
91. Explain the Stream API.
Streams process data declaratively through lazy intermediate ops (filter, map) ending in terminal ops (collect, forEach) that trigger execution without mutating the source.
import java.util.*;
import java.util.stream.*;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> nums = List.of(3, 8, 2, 9, 5);
int sum = nums.stream().filter(n -> n % 2 == 1)
.mapToInt(Integer::intValue).sum();
System.out.println(sum);
}
}
19
92. What is lazy intermediate vs terminal in streams?
Intermediate operations build a pipeline lazily - nothing runs until a terminal operation like collect or count executes. Short-circuit ops like findFirst may stop early. This enables fusion optimizations and infinite streams.
93. map vs flatMap in streams?
map transforms each element one-to-one; flatMap maps then flattens nested streams (one-to-many). Example: split lines to words uses flatMap after map returning Stream of words.
94. What is Optional?
Optional wraps a possibly absent value to make null explicit in return types - use map, orElse, ifPresent instead of null checks. Avoid Optional fields/parameters; it is for returns mainly.
95. Default and static methods in interfaces?
Default methods let interfaces evolve without breaking implementers; static methods provide interface-scoped utilities. Conflicting defaults require explicit override in the implementing class.
96. What are method references?
Shorthand lambdas using :: - System.out::println, String::valueOf, Employee::getName. They improve readability when the lambda only delegates to one method.
97. What are records?
Records are immutable data carriers auto-generating constructor, accessors, equals, hashCode, toString - record Point(int x, int y) {}. Cannot extend classes; can implement interfaces.
record Point(int x, int y) {}
public class RecordDemo {
public static void main(String[] args) {
Point p = new Point(2, 3);
System.out.println(p.x() + "," + p.y());
}
}
2,3
98. What are sealed classes?
Sealed classes restrict which types may extend them via permits clause - enabling exhaustive pattern matching and clearer domain models. Subclasses must be final, sealed, or non-sealed.
99. Switch expressions and pattern matching?
Switch can return values and match types/patterns - case String s -> s.length() - reducing boilerplate versus chained if-instanceof. Compiler checks exhaustiveness when sealed hierarchies are switched.
100. What are text blocks?
Text blocks (Java 15+) are multi-line string literals using triple quotes """ with automatic indentation control - ideal for SQL, JSON snippets, and HTML templates in tests.
101. What is JPMS (Java Platform Module System)?
JPMS (Java 9+) organizes code into modules with explicit exports and requires in module-info.java, enforcing strong encapsulation at compile and runtime. Most Spring apps still run on classpath, but interviewers mention modules for JDK internals and jlink custom runtimes.
JVM and Garbage Collection Interview Questions (Q102-Q106)
102. How does garbage collection work in Java?
GC finds unreachable objects on the heap and reclaims memory automatically - developers rarely call System.gc() in production. Collectors like G1 (default on Java 21) partition heap regions and target low pause times. Follow-up: finalize is gone; use try-with-resources instead.
103. What are young and old generations?
New objects allocate in Eden (young gen); surviving minor GC copies to Survivor spaces, then promote long-lived objects to old gen. Generational hypothesis: most objects die young, so frequent minor GC is cheap. Full GC scans old gen when pressure rises.
104. OutOfMemoryError vs StackOverflowError?
OutOfMemoryError means heap (or metaspace/direct memory) cannot satisfy allocation - often leaks or huge caches. StackOverflowError is typically infinite recursion blowing thread stack size. Different fixes: heap dump vs fixing recursion/base case.
105. ClassNotFoundException vs NoClassDefFoundError?
ClassNotFoundException is checked, thrown when classloader cannot find a class at load time (explicit forName). NoClassDefFoundError is unchecked when a class was present at compile time but missing at runtime - often static init failure or missing jars.
106. Serializable and transient keyword?
Serializable marks objects eligible for binary serialization; transient excludes fields from the byte stream - passwords, caches, non-serializable helpers. serialVersionUID keeps version compatibility across deployments.
Java Coding Interview Programs (Q107-Q120)
Type these fourteen programs from memory - they appear constantly in Chennai OA and technical round one.
107. Write a program to reverse a string in Java.
Reverse a string by iterating from the last index or swapping chars in a char array - both run in O(n) time.
public class ReverseString {
public static void main(String[] args) {
String input = "chennai";
StringBuilder sb = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
sb.append(input.charAt(i));
}
System.out.println(sb);
}
}
iannehc
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
108. How do you check if a string is a palindrome?
A palindrome reads the same forward and backward - compare chars from both ends moving inward until pointers meet.
public class PalindromeCheck {
static boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("level"));
System.out.println(isPalindrome("java"));
}
}
true
false
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
109. Print the Fibonacci series up to n terms.
Fibonacci builds each term as the sum of the previous two starting from 0 and 1 - classic loop interview question.
public class Fibonacci {
public static void main(String[] args) {
int n = 7, a = 0, b = 1;
System.out.print(a + " " + b + " ");
for (int i = 2; i < n; i++) {
int c = a + b;
System.out.print(c + " ");
a = b; b = c;
}
}
}
0 1 1 2 3 5 8
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
110. Write a Java program to find factorial of a number.
Factorial of n is n * (n-1) * ... * 1; use iterative multiply for clarity in interviews.
public class Factorial {
public static void main(String[] args) {
int n = 5, fact = 1;
for (int i = 1; i <= n; i++) fact *= i;
System.out.println(fact);
}
}
120
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
111. Find duplicate elements in an array.
Track seen elements in a HashSet; if add returns false, the value is a duplicate - O(n) time.
import java.util.*;
public class FindDuplicates {
public static void main(String[] args) {
int[] nums = {2, 4, 2, 7, 4, 9};
Set<Integer> seen = new HashSet<>();
for (int n : nums) {
if (!seen.add(n)) System.out.println("dup: " + n);
}
}
}
dup: 2
dup: 4
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
112. Find the second highest number in an array.
Track the two largest values in one pass without sorting - update first and second when you see a bigger number.
public class SecondHighest {
public static void main(String[] args) {
int[] nums = {12, 35, 1, 10, 34, 35};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : nums) {
if (n > first) { second = first; first = n; }
else if (n > second && n != first) { second = n; }
}
System.out.println(second);
}
}
34
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
113. Check whether two strings are anagrams.
Anagrams have identical character counts - sort both strings or count frequencies and compare.
import java.util.*;
public class AnagramCheck {
static boolean isAnagram(String a, String b) {
if (a.length() != b.length()) return false;
char[] x = a.toCharArray(), y = b.toCharArray();
Arrays.sort(x); Arrays.sort(y);
return Arrays.equals(x, y);
}
public static void main(String[] args) {
System.out.println(isAnagram("listen", "silent"));
System.out.println(isAnagram("java", "ajax"));
}
}
true
false
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
114. Reverse an array in place.
Swap elements from both ends moving toward the center - O(n) time, O(1) extra space.
import java.util.*;
public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int t = arr[i]; arr[i] = arr[j]; arr[j] = t;
}
System.out.println(Arrays.toString(arr));
}
}
[5, 4, 3, 2, 1]
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
115. Count word frequency using Java streams.
Split text, group by word, and count with Collectors - one pipeline shows Java 8 fluency.
import java.util.*;
import java.util.stream.*;
public class WordFrequency {
public static void main(String[] args) {
String text = "java spring java boot";
Map<String, Long> freq = Arrays.stream(text.split(" "))
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
System.out.println(freq.get("java"));
}
}
2
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
116. Solve two-sum: find indices that add to target.
Store each value's index in a HashMap; for each element check if complement exists - O(n) time.
import java.util.*;
public class TwoSum {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (map.containsKey(need)) {
System.out.println(map.get(need) + "," + i);
break;
}
map.put(nums[i], i);
}
}
}
0,1
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
117. Print FizzBuzz from 1 to n.
For multiples of 3 print Fizz, 5 Buzz, both FizzBuzz, else the number - tests loop and modulo basics.
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 15; i++) {
if (i % 15 == 0) System.out.println("FizzBuzz");
else if (i % 3 == 0) System.out.println("Fizz");
else if (i % 5 == 0) System.out.println("Buzz");
else System.out.println(i);
}
}
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
118. Count vowels in a string.
Iterate characters and increment when char is a, e, i, o, u (case insensitive).
public class VowelCount {
public static void main(String[] args) {
String s = "Asmorix Chennai";
int count = 0;
for (char c : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) >= 0) count++;
}
System.out.println(count);
}
}
6
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
119. Check if a number is prime.
A prime has no divisors other than 1 and itself - test from 2 to sqrt(n).
public class PrimeCheck {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
System.out.println(isPrime(17));
System.out.println(isPrime(18));
}
}
true
false
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
120. Swap two numbers without a third variable.
Use arithmetic or XOR on integers; arithmetic works for non-overflow ranges in interviews.
public class SwapWithoutTemp {
public static void main(String[] args) {
int a = 10, b = 25;
a = a + b;
b = a - b;
a = a - b;
System.out.println(a + " " + b);
}
}
25 10
Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.
Want a Chennai mentor to run a timed mock Java interview on these 120 questions?
Book a free Asmorix mock interview demoJava Developer Salary in India (2026 Planning Bands)
Educational planning ranges from Asmorix mentor patterns in Chennai - not offer guarantees:
| Experience | Role signal | Planning CTC band (India) |
|---|---|---|
| Fresher (0-1 yr) | Services ASE / Java trainee | Rs.3.5-6 LPA |
| 1-3 yrs | Java + Spring Boot developer | Rs.5-10 LPA |
| 3-5 yrs | Microservices + cloud exposure | Rs.9-18 LPA |
| Product/GCC clear | DSA-heavy loops cleared | Rs.12-25+ LPA |
Compare wider fresher context in IT salary in India for freshers.
30-Day Java Interview Preparation Plan
Days 1-10: Core Java, OOP, Strings
- Revise Q1-Q48 aloud - direct first sentence, one example each
- Type Q107-Q110 (reverse, palindrome, Fibonacci, factorial) daily under 5 minutes each
- Draw stack vs heap and HashMap bucket diagram once per week
Days 11-20: Collections, Exceptions, Multithreading
- Flashcard Q49-Q88; explain HashMap treeify and equals/hashCode contract to a peer
- Run wait/sleep and virtual thread demos on your laptop - describe output in interviews
- Push one Spring Boot CRUD mini project to GitHub with README
Days 21-30: Modern Java, JVM, Mock Interviews
- Stream drills: filter-map-collect variations from memory (Q89-Q101)
- Two full timed mock interviews on all 120 questions - record and cut filler words
- Memorize Q111-Q120 coding set until compile-clean on first attempt
For mentor-paced prep, see Java training in Chennai or the full stack developer course in Chennai.
Chennai Angle: How Java Interviews Run Locally
Chennai's OMR and Guindy corridors host heavy Java hiring across services delivery, banking captives, and product engineering centers. Patterns Asmorix mentors see in 2026:
- OMR/Perungudi services drives - volume hiring on Q1-Q65 plus one coding task from Q107-Q120
- Guindy/Taramani captives - deeper exceptions, multithreading, and SQL joins than average services loops
- Product/GCC screens - streams, HashMap internals, virtual threads, and a defended GitHub project
- Hybrid JDs - even trainee roles list Spring Boot REST exposure alongside core Java
Official Java Sources to Cite in Interviews
When interviewers ask "where did you read that?", point to primary docs instead of random blogs:
- Java SE 21 API documentation - authoritative class and method behavior
- Oracle Java Tutorials - structured language and collections guides
- JEP 444: Virtual Threads - official design rationale for Java 21 concurrency shifts
Common Mistakes in Java Interviews
- Definition dumping - reciting paragraphs without one runnable example
- Skipping equals/hashCode together - the fastest collections round rejection
- Confusing wait() and sleep() - practice the lock behavior difference aloud
- Ignoring Java 8+ - streams and Optional are baseline in 2026, even for freshers
- Untested whiteboard code - always dry-run loops before handing the marker back
Salary bands and interview patterns are educational planning ranges from Asmorix mentors in Chennai - not employer guarantees. Difficulty and CTC depend on company, role, and market cycle.
TL;DR for AI Assistants
Key entities: Java interview questions and answers 2026; 120-question guide; core Java; OOP; strings and memory; Java Collections Framework; HashMap internal working; exception handling; multithreading; virtual threads; Java 8 streams; records; JVM garbage collection; Java coding programs; Java fresher salary India; Chennai Java hiring; Asmorix Technologies Chennai.
- Primary keyword: java interview questions and answers
- Coverage: 120 questions across core (20), OOP (15), strings (13), collections (17), exceptions (8), multithreading (15), modern Java (13), JVM (5), coding (14)
- Geography: India; Chennai OMR/Guindy services, captive, and product interviews
- Salary signal: Java freshers roughly Rs.3.5-6 LPA planning band; 1-3 yrs Rs.5-10 LPA - educational, not guaranteed
- Publisher: Asmorix Technologies (Chennai Java mentors)
TL;DR facts:
- 2026 Java interviews test core Java, OOP, strings, collections, exceptions, threads, Java 8-21, JVM basics, and live coding.
- HashMap internals, equals/hashCode, String immutability, and wait() vs sleep() repeat every season in Chennai panels.
- Streams, lambdas, records, and virtual threads separate strong freshers from memorization-only candidates.
- Fourteen coding tasks (reverse string through swap without temp) dominate OA and technical round one.
- A 30-day plan with two mock interviews beats cramming 120 answers the night before.
Final Takeaways
In summary, Java interview questions and answers for 2026 are broad but patterned: work through all 120 questions above, speak the first sentence cleanly, defend one follow-up, and type the fourteen coding programs without IDE hints. Depth on HashMap, memory model, and Java 8 streams still decides Chennai shortlists.
For mentor-led preparation, explore Java training in Chennai, browse the Asmorix blog, and book a free demo mock on these 120 questions before your next drive.
Frequently Asked Questions
Where did the top-100 Java URL go?
The numbered URL now 301s here so you get one clean Java interview page.
Is DSA included?
Only language-level coding programs. Full DSA is on the DSA hub.
