Java Interview Questions & Answers

Java Interview Questions & Answers (2026) – Top 30 Questions for Freshers & Experienced

Table of Contents

⚡ AI Overview (Quick Answer)

To pass a Java interview in 2026, you need strong command over OOPs concepts, the Collections Framework, exception handling, multithreading, JVM internals, and modern features like records, streams, and virtual threads. Service companies (TCS, Infosys, Wipro) emphasize core Java and OOPs, while product companies add DSA and system design. This guide delivers 30+ real Java interview questions with model answers, comparison tables, salary data, and preparation strategy.


Introduction: The Language That Refuses to Retire

Every year, someone declares “Java is dying” — and every year, Java quietly powers the banking systems processing your salary, the Android apps on three billion devices, and the enterprise backends of nearly every Fortune 500 company. In 2026, Java remains one of the top three most-demanded skills in Indian IT hiring, and the Java technical round remains the great filter between candidates and offer letters.

Here is the truth nobody tells freshers: Java interviews are predictable. The same 30–40 core questions appear again and again, dressed in slightly different words. Panels at TCS, Infosys, Capgemini, Accenture, and Cognizant test fundamentals; product companies like Amazon and Flipkart wrap the same fundamentals inside coding problems. Master the questions below, and you will recognize 80% of whatever your interviewer asks.

Interview StageFocus AreaDifficulty
Aptitude/MCQ RoundOutput prediction, syntax, basicsEasy–Medium
Core Java RoundOOPs, String handling, Collections, ExceptionsMedium
Advanced RoundMultithreading, JVM, Java 8+ featuresMedium–Hard
Framework RoundSpring Boot, Hibernate, REST APIsMedium–Hard
Managerial + HRProjects, behavior, salary discussionMedium

If the framework round worries you, pair this article with our detailed Spring Boot Interview Questions & Answers guide — most Java jobs in 2026 are effectively Java + Spring Boot jobs.


Core Java Interview Questions for Freshers (Q1–Q12)

Q1. What is Java and why is it platform-independent?

Answer: Java is a high-level, object-oriented, class-based programming language developed by James Gosling at Sun Microsystems in 1995 (now owned by Oracle). Java achieves platform independence through its famous WORA principle — Write Once, Run Anywhere. Source code compiles into bytecode (.class files), which runs on the Java Virtual Machine (JVM). Since JVMs exist for Windows, Linux, and macOS, the same bytecode runs everywhere without recompilation. The official documentation lives at Oracle’s Java site.

Q2. Explain JDK vs JRE vs JVM.

Answer: This trio opens most fresher interviews:

ComponentFull FormWhat It ContainsWho Uses It
JVMJava Virtual MachineExecutes bytecode, handles memory & GCRuntime engine
JREJava Runtime EnvironmentJVM + core librariesEnd users running apps
JDKJava Development KitJRE + compiler (javac) + dev toolsDevelopers

One-liner to impress: “JDK is for development, JRE is for running, JVM is the engine inside both.”

Q3. What are the four pillars of OOPs in Java?

Answer: (1) Encapsulation — wrapping fields and methods in a class with private access and public getters/setters; (2) Inheritance — child classes extend parents using extends, enabling code reuse; (3) Polymorphism — one interface, many implementations: compile-time (method overloading) and runtime (method overriding); (4) Abstraction — exposing only essential behavior through abstract classes and interfaces. Always attach a real example: “In my banking project, SavingsAccount and CurrentAccount both extended Account and overrode calculateInterest() — that’s runtime polymorphism.”

Q4. What is the difference between method overloading and overriding?

Answer: Overloading means multiple methods with the same name but different parameter lists in the same class — resolved at compile time. Overriding means a subclass redefines a parent class method with the same signature — resolved at runtime via dynamic dispatch. Key rules for overriding: the access modifier cannot be more restrictive, the return type must be the same or covariant, and @Override annotation is best practice to catch typos.

Q5. Why are Strings immutable in Java?

Answer: Strings are immutable for several deliberate reasons: (1) String pool efficiency — identical literals share one object, saving memory; (2) Security — strings carry usernames, URLs, and file paths that must not change after validation; (3) Thread safety — immutable objects need no synchronization; (4) Hashcode caching — Strings cache their hash, making them fast, reliable HashMap keys. Follow-up trap: String s = new String(“hello”) creates two objects (one in pool, one in heap) if “hello” wasn’t pooled already.

Q6. String vs StringBuilder vs StringBuffer?

Answer:

ClassMutable?Thread-Safe?SpeedUse Case
StringNoYes (immutable)Slowest for concatenationFixed text
StringBuilderYesNoFastestSingle-threaded string building
StringBufferYesYes (synchronized)Slower than StringBuilderMulti-threaded string building

Model answer ending: “In loops, I always use StringBuilder — concatenating Strings in a loop creates a new object every iteration, which is O(n²).”

Q7. What is the difference between == and .equals() for objects?

Answer: == compares references (memory addresses) — are these the same object? .equals() compares logical content — when properly overridden, as in String and Integer. The golden contract: whenever you override equals(), you must override hashCode() too, or HashMap/HashSet behavior breaks because equal objects would land in different buckets.

Q8. Explain the difference between abstract class and interface.

Answer: An abstract class can have constructors, instance variables, and both abstract and concrete methods; a class extends only one abstract class. An interface defines a contract — since Java 8 it can include default and static methods, and since Java 9, private methods; a class can implement multiple interfaces. Rule of thumb to quote: “Abstract class = is-a relationship with shared state; interface = can-do capability. Bird is an abstract class; Flyable is an interface.”

Q9. What are constructors in Java? Can they be overloaded?

Answer: A constructor is a special block with the same name as the class and no return type, invoked automatically during object creation to initialize state. Yes — constructors can be overloaded with different parameter lists, and one constructor can call another using this(…) (constructor chaining). Constructors cannot be inherited, overridden, declared final, static, or abstract — common true/false MCQ material.

Q10. What is the final keyword?

Answer: final has three uses: a final variable becomes a constant (assigned once); a final method cannot be overridden by subclasses; a final class (like String) cannot be extended. Bonus depth: final reference variables can’t be reassigned, but the object they point to can still mutate — final List<String> list still allows list.add().

Q11. Explain exception hierarchy: checked vs unchecked exceptions.

Answer: All exceptions descend from Throwable, which splits into Error (fatal JVM problems like OutOfMemoryError — don’t catch these) and Exception. Checked exceptions (IOException, SQLException) must be declared or handled at compile time; unchecked exceptions (RuntimeException subclasses like NullPointerException, ArrayIndexOutOfBoundsException) indicate programming bugs and need no declaration. Best practice: use checked exceptions for recoverable conditions, unchecked for programming errors, and never swallow exceptions silently.

Q12. What is the difference between throw and throws?

Answer: throw is a statement used inside a method to actually raise an exception object (throw new IllegalArgumentException(“Invalid age”)). throws is a clause in the method signature declaring which checked exceptions the method may pass to its caller. One throws the ball; the other warns it might be thrown.


Java Collections & Intermediate Questions (Q13–Q21)

Q13. Explain the Java Collections Framework hierarchy.

Answer: The framework’s root interfaces are Collection (with children List, Set, Queue) and Map (separate hierarchy). Key implementations: ArrayList and LinkedList (List), HashSet, LinkedHashSet, TreeSet (Set), PriorityQueue and ArrayDeque (Queue), HashMap, LinkedHashMap, TreeMap (Map). Interviewers expect you to pick the right structure for a scenario: “Need insertion order with no duplicates? LinkedHashSet. Need sorted keys? TreeMap.”

Q14. ArrayList vs LinkedList — when to use which?

Answer:

OperationArrayListLinkedList
Random access (get)O(1)O(n)
Insert/delete at endAmortized O(1)O(1)
Insert/delete in middleO(n) shiftO(n) traversal + O(1) link change
MemoryCompact arrayExtra node pointers

Honest senior-level answer: “In practice I use ArrayList 95% of the time — modern CPUs love contiguous memory. LinkedList wins only for frequent head insertions or when implementing deques.”

Q15. How does HashMap work internally?

Answer: This is the most famous Java interview question. HashMap stores entries in an array of buckets. On put(key, value): (1) hashCode() of the key is computed and compressed to a bucket index; (2) if the bucket is empty, the entry is stored; (3) on collision, entries chain as a linked list; (4) since Java 8, a bucket converts to a red-black tree when chain length exceeds 8, improving worst case from O(n) to O(log n); (5) when size exceeds capacity × load factor (default 0.75), the table resizes (doubles) and entries rehash. get() reverses the process using hashCode() then equals().

Q16. HashMap vs Hashtable vs ConcurrentHashMap?

Answer: HashMap is non-synchronized, allows one null key, and is fastest for single-threaded use. Hashtable is legacy, fully synchronized (one big lock), and forbids nulls — avoid it. ConcurrentHashMap is the modern thread-safe choice: it uses fine-grained locking (bucket-level CAS operations since Java 8), allowing high concurrent throughput without locking the whole map.

Q17. What are Java 8 Streams and lambda expressions?

Answer: Lambda expressions (a, b) -> a + b provide concise implementations of functional interfaces (interfaces with a single abstract method, like Runnable, Comparator, Function). The Stream API enables declarative data processing: employees.stream().filter(e -> e.getSalary() > 50000).map(Employee::getName).collect(Collectors.toList()). Know intermediate operations (filter, map, sorted — lazy) vs terminal operations (collect, forEach, reduce — trigger execution), and parallel streams for multi-core processing.

Q18. What is the difference between Comparable and Comparator?

Answer: Comparable defines a class’s natural ordering via compareTo() implemented inside the class itself — one ordering per class. Comparator is an external ordering strategy via compare() — you can create unlimited comparators (sort employees by name, then by salary) without touching the class. Java 8 made comparators elegant: Comparator.comparing(Employee::getSalary).reversed().thenComparing(Employee::getName).

Q19. Explain fail-fast vs fail-safe iterators.

Answer: Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is structurally modified during iteration — they detect changes via a modCount. Fail-safe iterators (CopyOnWriteArrayList, ConcurrentHashMap) iterate over a snapshot or use weakly-consistent views, never throwing — at the cost of possibly stale data and extra memory.

Q20. What are generics and type erasure?

Answer: Generics (List<String>) provide compile-time type safety, eliminating casts and ClassCastExceptions. Type erasure means generic type information is removed at compile time — at runtime, List<String> and List<Integer> are both just List. This explains why you cannot do new T(), create generic arrays, or overload methods differing only in generic parameters. Wildcards: <? extends Number> (read/producer), <? super Integer> (write/consumer) — remember PECS: Producer Extends, Consumer Super.

Q21. What’s new in modern Java (17 → 21)?

Answer: Interviewers in 2026 expect awareness of: records (immutable data carriers replacing boilerplate POJOs), sealed classes (restricting which classes may extend a type), pattern matching for instanceof and switch, text blocks for multiline strings, and the headline feature of Java 21 — virtual threads (Project Loom), enabling millions of lightweight threads for high-concurrency servers without async complexity. Mentioning virtual threads instantly marks you as current.


Multithreading, JVM & Scenario Questions (Q22–Q30)

Q22. What is the difference between a process and a thread?

Answer: A process is an independent program with its own memory space; a thread is a lightweight unit of execution within a process, sharing the process’s heap but owning its own stack. Java creates threads by extending Thread or — preferred — implementing Runnable/Callable and submitting to an ExecutorService thread pool.

Q23. Explain synchronized, volatile, and atomic variables.

Answer: synchronized provides mutual exclusion plus visibility — only one thread enters the block/method per monitor lock. volatile guarantees visibility only — reads always see the latest write across threads — but not atomicity (volatile counter++ is still broken). AtomicInteger and friends use lock-free CAS (compare-and-swap) hardware instructions for atomic operations with better performance than locking. Classic question: “Is volatile enough for a counter?” Answer: No — use AtomicInteger or synchronization.

Q24. What is a deadlock and how do you prevent it?

Answer: Deadlock occurs when two or more threads wait forever for locks held by each other — thread A holds lock 1 wanting lock 2, while thread B holds lock 2 wanting lock 1. Prevention strategies: (1) acquire locks in a consistent global order; (2) use tryLock() with timeout from ReentrantLock; (3) minimize lock scope; (4) prefer concurrent collections and immutability over manual locking. Detecting one: thread dumps via jstack show “Found one Java-level deadlock.”

Q25. Explain JVM memory areas and garbage collection.

Answer: JVM memory divides into: Heap (objects; split into Young Generation — Eden + Survivor spaces — and Old Generation), Metaspace (class metadata, replaced PermGen since Java 8), Stack (per-thread frames with local variables), PC registers, and native method stacks. Garbage collection automatically reclaims unreachable objects: minor GCs clean the young generation frequently and cheaply; major GCs clean the old generation. Modern collectors: G1 (default, region-based, pause-target driven) and ZGC (sub-millisecond pauses for huge heaps).

Q26. What is the difference between heap and stack memory?

Answer: Stack memory is per-thread, stores method frames, local primitives, and object references, and is automatically freed when methods return — fast but small (StackOverflowError on deep recursion). Heap is shared across threads, stores all objects, and is managed by the garbage collector (OutOfMemoryError when exhausted). Quick example: in Employee e = new Employee(), the reference e lives on the stack; the Employee object lives on the heap.

Q27. Scenario: Your Java application’s memory keeps growing in production. How do you investigate?

Answer: (1) Confirm with monitoring — heap usage graphs trending upward after GC indicates a leak; (2) capture a heap dump (jmap -dump or on OOM via -XX:+HeapDumpOnOutOfMemoryError); (3) analyze in Eclipse MAT to find dominator trees — common culprits: static collections that only grow, unclosed resources, listener registrations never removed, ThreadLocal misuse; (4) fix and verify with load testing. This structured story is exactly what senior panels want. Deployment-side issues often follow this question, so our AWS Interview Questions & Answers and Cloud Computing Interview Questions guides make perfect companion reading.

Q28. How do you connect Java to a database, and what is connection pooling?

Answer: Via JDBC — load the driver, obtain a Connection, use PreparedStatement (always, to prevent SQL injection), process the ResultSet, and close resources with try-with-resources. In real applications, opening connections per request is too costly, so connection pools (HikariCP — Spring Boot’s default) maintain reusable connections. ORMs like Hibernate/JPA map objects to tables above JDBC. Brush up the database side with our Basic SQL Interview Questions guide — Java rounds nearly always include SQL.

Q29. How does Java compare with Python for backend development?

Answer: A balanced answer: Java offers static typing, superior raw performance, mature concurrency (now with virtual threads), and dominance in large enterprise/banking systems. Python wins on development speed, scripting, and AI/ML ecosystem integration. Many teams use both — Java for core transactional services, Python for data pipelines. Preparing for both? Our companion guide on Python interview questions pairs perfectly with this one.

Q30. What questions should YOU ask the interviewer?

Answer: Smart reverse-questions: “Which Java version and frameworks does the team run in production?”, “How is code review and testing culture here?”, “What does success look like in the first 90 days?” Asking nothing signals low interest; asking about technology and growth signals seriousness.


Java Developer Salary in India (2026)

ExperienceRoleAverage Annual Salary (INR)
0–2 yearsJunior Java Developer₹3.5 – 6.5 LPA
2–5 yearsJava / Backend Developer₹7 – 15 LPA
5–9 yearsSenior Developer / Tech Lead₹15 – 30 LPA
9+ yearsArchitect₹30 – 55+ LPA

Indicative market ranges; actuals vary by company, city, and skill depth (Spring Boot + Microservices + Cloud commands premiums).


7 Battle-Tested Tips to Crack the Java Round

  1. Master the “internal working” trio: HashMap internals, String pool, and JVM memory — these three appear in nearly every interview above fresher level.
  2. Write code without an IDE. Panels often use plain editors or whiteboards; practice syntax from memory.
  3. Prepare one strong project narrative covering OOPs decisions, collections used, and one bug you debugged.
  4. Practice 50 output-prediction questions — service company MCQ rounds live on these.
  5. Learn Java 8+ features deeply — streams and lambdas are now mandatory, not optional.
  6. Pair Java with Spring Boot — read our Spring Boot Interview Questions guide next.
  7. Don’t neglect the HR round — rehearse answers using our HR Interview Questions for Freshers guide.

For authoritative references, keep the official Java documentation and Baeldung tutorials bookmarked throughout your preparation.


📚 Recommended Resources (Affiliate Section)

ResourceBest ForLink
“Head First Java” (Book)Absolute beginners[Check Price on Amazon → Affiliate Link]
“Effective Java” by Joshua BlochInterview-grade best practices[Check Price on Amazon → Affiliate Link]
Java Masterclass (Udemy)Structured video learning[Enroll Now → Affiliate Link]
“Java Concurrency in Practice”Multithreading mastery[Check Price on Amazon → Affiliate Link]

Affiliate Disclosure: Some links above are affiliate links. Interview Questions Hub may earn a small commission on purchases made through them, at no additional cost to you. We recommend only resources we trust to genuinely improve your preparation.


Frequently Asked Questions (FAQ)

Q1. Is core Java enough to get a job in 2026? Core Java gets you through fresher rounds at service companies, but adding Spring Boot, SQL, Git, and REST API knowledge dramatically improves both selection chances and starting salary.

Q2. How long does it take to prepare for a Java interview? With existing college knowledge, plan 4–6 weeks: two weeks core Java + OOPs, one week collections + Java 8 features, one week multithreading + JVM, and the rest for mock interviews and projects.

Q3. Which is better for freshers — Java or Python? Both open doors. Java offers more volume in enterprise/service-company hiring in India; Python dominates data and automation roles. Choose based on target roles, not hype — and the fundamentals transfer.

Q4. Do I need to know Java 21 features? You won’t be rejected for not knowing them, but mentioning records, sealed classes, and virtual threads signals you stay current — a major differentiator in 2026 interviews.

Q5. Are coding rounds in Java interviews hard? Service companies ask easy pattern/string/array problems; product companies ask LeetCode easy–medium DSA. Twenty problems across arrays, strings, HashMap usage, and recursion cover most rounds.


Conclusion

Java interviews are won through depth, not breadth — the candidate who can explain how HashMap resizes beats the one who memorized fifty definitions. Drill these 30 questions, build muscle memory with daily coding, and stitch your knowledge into project stories interviewers remember. Continue your preparation with our Spring Boot guide and SQL questions — then walk in and own that interview room. Your Java career compiles successfully from here!


Disclaimer: The interview questions, answers, and salary figures presented in this article are for educational and preparation purposes, compiled from commonly reported interview experiences and publicly available market data. Actual interview content, hiring processes, and compensation differ by company, role, and location. Interview Questions Hub does not guarantee employment or interview outcomes. All trademarks belong to their respective owners.

Leave a Reply

Your email address will not be published. Required fields are marked *