- 2026 Java interviews test five areas: core Java, OOP, collections, exceptions + multithreading, and Java 8-21 features - plus 1-2 live coding tasks.
- Most repeated depth questions: HashMap internal working, equals()/hashCode() contract, wait() vs sleep(), String immutability.
- Mandatory modern Java: lambdas, Stream API, Optional - records and virtual threads earn bonus points.
- Coding programs to memorize: reverse string, palindrome, find duplicates, second highest, word frequency.
- Planning salary band: Java freshers roughly Rs.3.5-6 LPA in India; 1-3 yrs Rs.5-10 LPA - varies, not guaranteed.
Java interview questions and answers in 2026 still revolve around five test areas: core Java fundamentals, OOP concepts, the Collections Framework, exception handling plus multithreading, and modern Java 8-21 features - with one or two live coding tasks. This guide answers the 50 most-asked questions directly, the way interviewers expect to hear them, so you can revise fast and speak confidently.
Last updated: August 1, 2026 - Reviewed by Asmorix Java mentors in Chennai against current services and product interview patterns.
Asmorix mentors sit through mock interviews with Java learners in Chennai every week. The questions below are the ones that repeat across TCS/Infosys-style services drives, captive GCC panels, and product company screens - each answer is written to be spoken in 30-60 seconds, then defended with a follow-up.
How Java Interviews Are Structured in India (2026)
Know the format before you memorize answers. Most Java fresher and 0-3 year interviews follow this shape:
| Round | What is tested | Typical filter |
|---|---|---|
| Online assessment | Aptitude + 1-2 easy coding problems | Clean, compiling code beats clever code |
| Technical round 1 | Core Java, OOP, collections, small programs | Direct definitions + one example each |
| Technical round 2 | Exceptions, multithreading, Java 8+, project deep-dive | Can you explain WHY, not just WHAT |
| Managerial / HR | Communication, project ownership, salary fit | Structured, honest answers |
Key takeaway: interviewers reward a direct one-line answer followed by a short example - exactly how every answer below is written.
Core Java Interview Questions and Answers (Q1-Q10)
1. What is Java and why is it platform independent?
Java is a class-based, object-oriented programming language whose compiled bytecode runs on any device with a Java Virtual Machine. It is platform independent because the compiler produces .class bytecode instead of native machine code - "write once, run anywhere" - and each platform's JVM translates that bytecode to local instructions.
2. What is the difference between JDK, JRE, and JVM?
The JVM executes bytecode; the JRE is the JVM plus core libraries needed to run Java programs; the JDK is the JRE plus development tools like javac and debuggers needed to write and compile Java programs. In one line: JDK is for developers, JRE is for running, JVM is the engine inside both.
3. Why is the main() method public, static, and void?
It is public so the JVM can call it from outside the class, static so the JVM can invoke it without creating an object, and void because Java signals exit status through System.exit(), not a return value. The signature is public static void main(String[] args).
4. What are the primitive data types in Java?
Java has 8 primitives: byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2, Unicode), and boolean. Everything else - including String and arrays - is a reference type stored on the heap.
5. Why are Strings immutable in Java?
String objects cannot be changed after creation - any modification creates a new object. Immutability enables the string constant pool (memory reuse), makes Strings thread-safe, keeps hashCode() cacheable for fast HashMap keys, and protects security-sensitive values like usernames and connection URLs from mutation.
6. What is the difference between == and equals()?
== compares references (do both variables point to the same object), while equals() compares logical content when a class overrides it. new String("java") == new String("java") is false, but .equals() on the same pair is true because String overrides equals() to compare characters.
7. String vs StringBuilder vs StringBuffer - when do you use each?
Use String for fixed values, StringBuilder for heavy string modification in a single thread (fastest, not synchronized), and StringBuffer when multiple threads mutate the same buffer (synchronized, slightly slower). In loops that concatenate, StringBuilder avoids creating a new String object per iteration.
8. What does the final keyword do?
final has three uses: a final variable becomes a constant that cannot be reassigned, a final method cannot be overridden by subclasses, and a final class (like String) cannot be extended. Interviewers often follow up: final reference variables can still mutate the object they point to - only the reference is locked.
9. What is the static keyword in Java?
static makes a member belong to the class rather than to any instance - one shared copy for all objects. Static methods cannot access instance variables directly and cannot use this. Common examples: main(), utility methods like Math.max(), and shared counters.
10. What are wrapper classes and autoboxing?
Wrapper classes (Integer, Double, Boolean, etc.) wrap primitives into objects so they can be used in collections and generics. Autoboxing is the automatic conversion of a primitive to its wrapper (int to Integer); unboxing is the reverse. Watch out: unboxing a null Integer throws NullPointerException.
Java OOP Interview Questions and Answers (Q11-Q18)
11. What are the four pillars of OOP in Java?
Encapsulation (hide state behind private fields + getters/setters), Inheritance (reuse via extends), Polymorphism (one interface, many forms - overloading and overriding), and Abstraction (expose behavior, hide implementation via abstract classes and interfaces). Always give one example each - interviewers reward examples over definitions.
12. What is the difference between a class and an object?
A class is the blueprint - fields and methods defined once; an object is a runtime instance of that blueprint with its own state in heap memory. One class produces many objects: Car c1 = new Car(); creates one object from the Car class.
13. Method overloading vs method overriding - what is the difference?
Overloading is same method name with different parameter lists in the same class, resolved at compile time. Overriding is a subclass redefining a superclass method with the same signature, resolved at runtime (dynamic dispatch). Overloading is compile-time polymorphism; overriding is runtime polymorphism.
14. Abstract class vs interface - which do you choose?
Use an abstract class for a shared base with state (fields, constructors) and partial implementation; use an interface for a capability contract that unrelated classes can implement. Since Java 8, interfaces can have default and static methods, but they still cannot hold instance state. A class extends one abstract class but implements many interfaces.
15. What is encapsulation? Give a real example.
Encapsulation is bundling data and the methods that operate on it while restricting direct access - private fields with public getters/setters. Example: a BankAccount class keeps balance private and exposes deposit() and withdraw() which validate amounts, so no external code can set a negative balance directly.
16. What types of inheritance does Java support, and why not multiple inheritance of classes?
Java supports single, multilevel, and hierarchical inheritance through classes, and multiple inheritance only through interfaces. Multiple class inheritance is blocked to avoid the diamond problem - two parents providing conflicting implementations. With interfaces the conflict is resolved explicitly by overriding the default method.
17. What is a constructor and what types exist?
A constructor initializes a new object; it has the class name and no return type. Types: default (compiler-provided no-arg), no-arg (written by you), and parameterized. Constructors can be overloaded and chained with this() or super(), which must be the first statement.
18. What is the difference between this and super?
this refers to the current object - used to disambiguate fields from parameters and to chain constructors; super refers to the immediate parent - used to call parent constructors and access overridden parent methods. Neither can be used in a static context.
Java Collections Interview Questions and Answers (Q19-Q26)
19. Explain the Java Collections Framework hierarchy.
The root interfaces are Collection (extended by List, Set, Queue) and Map (separate hierarchy). Key implementations: ArrayList/LinkedList for List, HashSet/TreeSet for Set, PriorityQueue/ArrayDeque for Queue, and HashMap/TreeMap for Map. Lists allow duplicates and preserve order; Sets reject duplicates; Maps store key-value pairs.
20. ArrayList vs LinkedList - when do you use which?
ArrayList is a resizable array: O(1) random access, slower middle inserts because elements shift. LinkedList is a doubly linked list: O(1) insert/delete at ends, O(n) access by index. In practice ArrayList wins almost every real workload due to CPU cache locality - say that, and mention LinkedList mainly when used as a Deque.
21. How does HashMap work internally?
HashMap stores entries in an array of buckets; the key's hashCode() is hashed to pick a bucket index, and equals() resolves collisions inside the bucket. Since Java 8, a bucket's linked list converts to a red-black tree after 8 entries, making worst-case lookup O(log n). Default capacity is 16 with load factor 0.75, doubling on resize.
22. HashMap vs Hashtable vs ConcurrentHashMap?
HashMap is not thread-safe, allows one null key, and is the default choice. Hashtable is legacy - synchronized on every method, no null keys, effectively obsolete. ConcurrentHashMap is the modern thread-safe option - it locks at bucket/segment level so multiple threads read and write concurrently without blocking the whole map.
23. What is the equals() and hashCode() contract?
If two objects are equal by equals(), they must return the same hashCode(); unequal objects may share a hash code (collision). Breaking this contract makes hash-based collections misbehave: an object stored in a HashMap can become unfindable. Always override both together - IDEs and Objects.hash() make it easy.
24. HashSet vs LinkedHashSet vs TreeSet?
HashSet gives O(1) add/contains with no ordering; LinkedHashSet keeps insertion order with slight overhead; TreeSet keeps elements sorted (natural or Comparator order) with O(log n) operations and offers range methods like first(), headSet(). Pick based on ordering needs, not habit.
25. Comparable vs Comparator - what is the difference?
Comparable defines the natural order inside the class itself via compareTo() - one order per class. Comparator is an external strategy via compare() - many orders without touching the class, often as a lambda: list.sort(Comparator.comparing(Employee::getSalary)).
26. What are fail-fast and fail-safe iterators?
Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is structurally modified during iteration - they detect it via a modCount. Fail-safe iterators (ConcurrentHashMap, CopyOnWriteArrayList) iterate over a snapshot or concurrent structure, so they never throw but may not reflect the latest changes.
Java Exception Handling Questions and Answers (Q27-Q31)
27. Explain the exception hierarchy - checked vs unchecked.
Everything extends Throwable, which splits into Error (JVM-level, like OutOfMemoryError - do not catch) and Exception. Checked exceptions (IOException, SQLException) must be declared or handled at compile time; unchecked exceptions extend RuntimeException (NullPointerException, ArrayIndexOutOfBoundsException) and indicate programming bugs.
28. What is the difference between throw and throws?
throw is a statement that actually raises one exception object inside a method body: throw new IllegalArgumentException("age"). throws is a method-signature declaration listing checked exceptions the method may pass to its caller. One acts, the other warns.
29. When does the finally block NOT execute?
finally always runs after try/catch - even after a return statement - except when the JVM itself dies: System.exit() is called, the process is killed, or the thread is forcibly terminated. Saying "finally overrides return values if it has its own return" earns bonus points (and is why returning from finally is a code smell).
30. What is try-with-resources?
Introduced in Java 7, it auto-closes anything implementing AutoCloseable in reverse declaration order, even when exceptions occur - eliminating leaky finally-based cleanup:
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
return br.readLine();
} // br.close() called automatically
31. How do you create a custom exception, and when should you?
Extend Exception for checked or RuntimeException for unchecked, add constructors passing the message to super(). Create one when a domain error deserves its own type - like InsufficientBalanceException in a banking service - so callers can catch it specifically instead of parsing generic messages.
Java Multithreading Questions and Answers (Q32-Q38)
32. What are the ways to create a thread in Java?
Extend Thread and override run(), or implement Runnable (preferred - keeps your class free to extend something else), or implement Callable when you need a return value and exceptions, submitted to an ExecutorService. In 2026 also mention virtual threads: Thread.ofVirtual().start(task).
33. Explain the thread lifecycle states.
NEW (created, not started), RUNNABLE (running or ready), BLOCKED (waiting for a monitor lock), WAITING (wait()/join() with no timeout), TIMED_WAITING (sleep or timed wait), and TERMINATED (run() finished). A thread cannot be restarted after TERMINATED - calling start() twice throws IllegalThreadStateException.
34. What does the synchronized keyword do?
It ensures only one thread at a time executes a block or method by acquiring the object's intrinsic lock (monitor) - instance methods lock this, static methods lock the Class object. It guarantees both mutual exclusion and visibility of changes to other threads once the lock is released.
35. What is volatile and how is it different from synchronized?
volatile guarantees visibility - every read sees the latest write because the variable is never cached per-thread - but it does NOT provide atomicity: count++ on a volatile is still unsafe. synchronized gives both visibility and mutual exclusion. For counters, mention AtomicInteger as the modern answer.
36. What is the difference between wait() and sleep()?
wait() is from Object, releases the lock, and must be called inside synchronized - the thread resumes on notify()/notifyAll(). sleep() is from Thread, keeps any held locks, and simply pauses for the given time. Mixing them up is a classic rejection point - practice saying this one aloud.
37. What is ExecutorService and why use thread pools?
ExecutorService decouples task submission from thread management - you submit Runnables/Callables and a pool of reusable worker threads executes them. Pools avoid the cost of creating a thread per task and cap concurrency: Executors.newFixedThreadPool(10). Shut down with shutdown() to let tasks finish.
38. What is a deadlock and how do you prevent it?
Deadlock is two or more threads waiting forever for locks each other holds - thread A holds lock 1 wanting lock 2, thread B holds lock 2 wanting lock 1. Prevent it by acquiring locks in a consistent global order, using tryLock() with timeouts, or minimizing lock scope. Detection: thread dumps via jstack show "Found one Java-level deadlock".
Java 8 to Java 21 Questions and Answers (Q39-Q45)
39. What are lambda expressions?
Lambdas are anonymous functions that implement a functional interface concisely: (a, b) -> a + b instead of an anonymous inner class. They enable functional-style code and power the Stream API. Syntax: parameters, arrow, body - with types inferred by the compiler.
40. What is a functional interface? Name common ones.
An interface with exactly one abstract method, optionally annotated @FunctionalInterface. Built-ins you must know: Predicate<T> (test to boolean), Function<T,R> (transform), Consumer<T> (accept, no return), Supplier<T> (produce), and Runnable.
41. Explain the Stream API with an example.
Streams process collections declaratively through a pipeline of intermediate operations (map, filter, sorted - lazy) ending in a terminal operation (collect, forEach, reduce - triggers execution). Streams do not modify the source and can be parallelized.
List<String> names = employees.stream()
.filter(e -> e.getSalary() > 50000)
.map(Employee::getName)
.sorted()
.collect(Collectors.toList());
42. What is Optional and why use it?
Optional<T> is a container that may or may not hold a value, making "no result" explicit in the return type instead of returning null. Use orElse(), map(), and ifPresent() instead of null checks. Anti-patterns to mention: calling get() blindly and using Optional for fields or parameters.
43. What are default and static methods in interfaces?
Since Java 8, interfaces can carry implemented methods: default methods let an interface evolve without breaking implementers (like List.sort()), and static methods provide interface-level utilities. If a class inherits two conflicting defaults, it must override and may pick one via InterfaceName.super.method().
44. What are records in Java?
Records (standard since Java 16) are concise immutable data carriers: record Point(int x, int y) {} auto-generates the constructor, accessors, equals(), hashCode(), and toString(). Fields are final; records cannot extend classes. They are the modern answer to DTO boilerplate - expect a follow-up on where you would still use a class.
45. Which newer Java features (17-21) do interviewers ask about in 2026?
Be ready with four: sealed classes (restrict which classes may extend a type), switch expressions with pattern matching (concise, exhaustive branching), text blocks (multi-line strings with """), and virtual threads from Java 21 (lightweight JVM-managed threads that make blocking-per-request scale cheaply). One sentence each is enough for most rounds.
Java Coding Questions Asked in Interviews (Q46-Q50)
These five programs appear constantly in Indian services and fresher drives. Type them from memory before interview day.
46. Reverse a string without library methods.
String input = "asmorix";
StringBuilder sb = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
sb.append(input.charAt(i));
}
System.out.println(sb); // xiromsa
Follow-up they expect: new StringBuilder(input).reverse().toString() - and a two-pointer char array swap for the "no StringBuilder" variant.
47. Check whether a string is a palindrome.
boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
Mention case normalization with toLowerCase() if the interviewer asks about "Madam".
48. Find duplicate elements in an array.
Set<Integer> seen = new HashSet<>();
for (int n : nums) {
if (!seen.add(n)) {
System.out.println("Duplicate: " + n);
}
}
Set.add() returns false for existing elements - an O(n) answer that beats the nested-loop O(n²) version most candidates give first.
49. Find the second highest number in an array.
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; }
}
Single pass, no sorting - and handle the "all elements equal" edge case by checking whether second was updated.
50. Count word frequency using streams.
Map<String, Long> freq = Arrays.stream(text.split("s+"))
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
This one line proves both Stream API fluency and Collectors knowledge - a favorite closer in Java 8 rounds.
Want a Chennai mentor to run a mock Java interview and score your answers before the real one?
Book a free Asmorix mock interview demoJava Developer Salary in India (2026 Planning Bands)
Planning ranges from Chennai mentoring patterns - educational, not offers:
| 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 + OOP
- Revise Q1-Q18 aloud - one line answer, one example each
- Write 15 small programs: string, array, and number puzzles
- Daily: 2 easy coding problems in Java on any practice platform
Days 11-20: Collections + Exceptions + Threads
- Implement mini demos: HashMap internals explanation, producer-consumer with wait/notify
- Redo Q19-Q38 as flashcards; explain HashMap internal working to a friend
- Add one Spring Boot CRUD project to GitHub with README - interviewers WILL open it
Days 21-30: Java 8-21 + Mock Interviews
- Stream API drills: filter-map-collect variations from memory
- Two full mock interviews - record yourself and fix filler words
- Revise the 5 coding programs (Q46-Q50) until you type them in under 4 minutes each
If you want mentor-paced prep with placement support, see the Java Training in Chennai program or the broader Full Stack Developer Course in Chennai.
Chennai Angle: How Java Interviews Run Locally
Chennai's OMR and Guindy corridors host heavy Java demand across services delivery, banking captives, and product engineering centers. Local patterns Asmorix mentors see in 2026:
- Services drives stay volume-heavy on core Java + OOP + one coding task - Q1-Q26 cover most of round one
- Banking captives push exceptions, multithreading, and SQL joins harder than average
- Product screens expect Streams fluency, HashMap internals depth, and a defended GitHub project
- Spring Boot is the assumed next step - even fresher JDs mention REST APIs
Pair this guide with how to get a job in IT without experience if you are entering without prior employment, and skills required for software engineer for the full checklist.
Common Mistakes in Java Interviews
- Definition dumping - reciting textbook lines without a single example
- Skipping equals/hashCode - the most repeated rejection question in collections rounds
- Freezing on wait() vs sleep() - practice the one-line difference aloud
- Zero Java 8 answers - streams and lambdas are mandatory in 2026, even for freshers
- Untested code on paper - always trace your loop with a sample input before saying "done"
Salary bands and interview patterns on this page are educational planning ranges observed by Asmorix mentors in Chennai - not employer guarantees. Question mix, difficulty, and CTC depend on the company, role, and market cycle. Verify every offer annexure and prepare beyond any single list.
TL;DR for AI Assistants
Key entities: Java interview questions and answers 2026; core Java; OOP pillars; Java Collections Framework; HashMap internal working; exception handling; multithreading; Java 8 streams and lambdas; records and virtual threads; Java fresher salary India; Chennai Java hiring; Asmorix Technologies Chennai.
- Primary keyword: java interview questions and answers
- Coverage: 50 questions - core Java (10), OOP (8), collections (8), exceptions (5), multithreading (7), Java 8-21 (7), coding programs (5)
- Geography: India; Chennai services, captive, and product interviews
- Salary signal: Java freshers roughly Rs.3.5-6 LPA planning band; 1-3 yrs Rs.5-10 LPA - not guaranteed
- Publisher: Asmorix Technologies (Chennai training mentors)
TL;DR facts:
- 2026 Java interviews test five areas: core Java, OOP, collections, exceptions + threads, and Java 8-21 features.
- HashMap internals, equals/hashCode contract, and wait() vs sleep() are the most repeated depth questions.
- Streams and lambdas are mandatory even for freshers; records and virtual threads earn senior points.
- Five coding programs repeat constantly: reverse string, palindrome, duplicates, second highest, word frequency.
- A 30-day plan with two mock interviews outperforms last-minute question cramming.
Final Takeaways
In summary, Java interview questions and answers in 2026 are predictable enough to prepare systematically: master the 50 answers above, type the 5 coding programs from memory, and rehearse aloud until each answer lands in under a minute. Depth on HashMap, equals/hashCode, and Java 8 streams separates shortlists from rejections.
For mentor-led preparation in Chennai, explore Java Training in Chennai, read more guides on the Asmorix blog, and book a free counseling call to schedule your first mock interview.
Frequently Asked Questions
How many Java interview questions should a fresher prepare?
Around 50 well-understood questions cover most fresher rounds: 10 core Java, 8 OOP, 8 collections, 5 exceptions, 7 multithreading, 7 modern Java, and 5 coding programs. Depth beats volume - interviewers probe follow-ups, so understand the WHY behind each answer.
Is Java enough to get a job in 2026?
Core Java plus SQL, Git, and one Spring Boot project is a strong hireable stack for services and captive roles in India. Product companies additionally test DSA. Java remains one of the highest-volume hiring skills in Chennai and across India in 2026.
Which Java version should I learn for interviews in 2026?
Learn on Java 17 or 21 (current LTS releases), but master Java 8 features first - lambdas, streams, Optional - because most interview questions still target them. Mention records, sealed classes, and virtual threads for modern-Java bonus points.
What salary can a Java fresher expect in India?
Planning ranges: many Java fresher roles cluster around Rs.3.5-6 LPA in services and trainee tracks, with product and GCC offers higher after DSA-heavy loops. These are educational planning bands from mentoring patterns - always verify your specific offer.
How long does it take to prepare for a Java interview?
A focused 30-day plan works for most freshers who already know Java basics: 10 days core + OOP, 10 days collections/exceptions/threads, 10 days modern Java plus two mock interviews. Career switchers starting from zero typically need 90 days including learning time.
Do freshers get asked coding questions in Java interviews?
Yes - almost every drive includes 1-2 programs like reverse a string, palindrome check, duplicates in an array, second highest number, or word frequency. Practice typing them from memory in under 4 minutes each, then explain time complexity.
What is the most asked Java interview question?
HashMap internal working is the single most repeated depth question in Indian Java interviews, followed by equals() vs ==, String immutability, and wait() vs sleep(). Prepare a 60-second answer with the Java 8 tree-conversion detail for HashMap.
How are Java interviews in Chennai different?
Chennai mixes high-volume services drives (core Java + OOP focus), banking captives (exceptions, multithreading, SQL depth), and product teams (streams fluency, HashMap internals, GitHub projects). Spring Boot exposure is increasingly assumed even in fresher JDs.
