{jsonbody.com}

Top 50 Java Interview Questions & Answers

Top 50 Java interview questions and answers for freshers and experienced developers: OOP, JVM, collections, multithreading, Java 8 streams and lambdas.

Loading…

Core Java & the JVM

Q1. What is the difference between JDK, JRE and JVM?

The JVM runs Java bytecode. The JRE is the JVM plus the standard libraries needed to run programs. The JDK adds development tools such as the javac compiler and debugger.

Q2. Why is Java platform independent?

Java code compiles to bytecode, not to machine code. Any device with a JVM can run that bytecode, so the same .class files work on Windows, Linux and macOS.

Q3. What are the main memory areas of the JVM?

The heap stores objects and is shared by all threads. Each thread has its own stack for method calls and local variables. The metaspace stores class metadata.

Q4. What is garbage collection?

The JVM automatically frees memory used by objects that are no longer reachable. Modern collectors such as G1 and ZGC split the heap into regions to keep pauses short.

Q5. What is the difference between == and equals()?

== compares references for objects, so it checks whether two variables point to the same object. equals() compares content when a class overrides it, as String does.

Q6. Why must hashCode() be overridden with equals()?

Hash-based collections such as HashMap use hashCode() to find the bucket, then equals() to find the key. Equal objects must have equal hash codes, or lookups fail.

Q7. Why is String immutable in Java?

Immutability lets strings be shared safely in the string pool, cached as hash keys and passed between threads without synchronisation. It also prevents security issues with values such as file paths.

Q8. What is the difference between String, StringBuilder and StringBuffer?

String is immutable. StringBuilder is mutable and fast, for building strings in one thread. StringBuffer is mutable and synchronised, so it is thread-safe but slower.

Q9. What is the difference between final, finally and finalize?

final makes a variable unchangeable, a method not overridable or a class not extendable. finally is a block that always runs after try. finalize was a cleanup method, now deprecated.

Q10. What is autoboxing?

Automatic conversion between primitives and their wrapper classes, such as int to Integer. Unboxing a null wrapper throws a NullPointerException.

Object-Oriented Programming

Q11. What are the four pillars of OOP?

Encapsulation hides internal state behind methods. Inheritance lets a class reuse another's behaviour. Polymorphism lets one interface have many implementations. Abstraction exposes what an object does, not how.

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

Overloading means methods with the same name but different parameters in one class, resolved at compile time. Overriding means a subclass replaces a parent method with the same signature, resolved at runtime.

Q13. What is the difference between an abstract class and an interface?

An abstract class can have state, constructors and any mix of methods, and a class extends only one. An interface defines a contract, can have default and static methods, and a class can implement many.

Q14. Why does Java not support multiple inheritance of classes?

To avoid the diamond problem, where two parents define the same method and the child cannot tell which to use. Interfaces allow multiple inheritance of type, and a class must resolve conflicting default methods.

Q15. What does the static keyword mean?

A static field or method belongs to the class rather than an instance, so it is shared by all objects and called through the class name. Static methods cannot use this.

Q16. What is the difference between this and super?

this refers to the current object. super refers to the parent class, to call its constructor or an overridden method.

Q17. What are access modifiers in Java?

public is visible everywhere, protected in the package and subclasses, package-private (no modifier) in the package only, and private only inside the class.

Q18. What is a constructor, and can it be private?

A special method that initialises a new object and has no return type. A private constructor stops other classes creating instances, which singletons and utility classes use.

Q19. What is composition, and why favour it over inheritance?

Composition means a class holds instances of other classes instead of extending them. It keeps classes loosely coupled and flexible, while deep inheritance chains become fragile.

Q20. What is an immutable class, and how do you create one?

A class whose state cannot change after creation. Make the class final, fields private final, add no setters, and copy mutable inputs and outputs. Java record types are a concise way to do this.

Collections & Generics

Q21. What is the Java Collections Framework?

The set of interfaces such as List, Set, Map and Queue, with implementations such as ArrayList, HashSet and HashMap, plus utility classes like Collections.

Q22. What is the difference between ArrayList and LinkedList?

ArrayList is backed by an array, so reading by index is fast but inserting in the middle is slow. LinkedList is a doubly linked list, so inserting at the ends is fast but reading by index is slow. ArrayList is usually the better choice.

Q23. How does HashMap work internally?

It stores entries in an array of buckets chosen by the key's hash code. Keys in the same bucket form a linked list, which turns into a balanced tree when it grows large. The array doubles when it passes its load factor of 0.75.

Q24. What is the difference between HashMap, LinkedHashMap and TreeMap?

HashMap has no order. LinkedHashMap keeps insertion order. TreeMap keeps keys sorted, with O(log n) operations.

Q25. What is the difference between HashMap and ConcurrentHashMap?

HashMap is not thread-safe. ConcurrentHashMap allows safe concurrent reads and writes with fine-grained locking, and does not accept null keys or values.

Q26. What is the difference between Comparable and Comparator?

Comparable defines a class's natural order through compareTo. Comparator defines a separate order outside the class, such as Comparator.comparing(User::getAge).

Q27. What are fail-fast and fail-safe iterators?

Fail-fast iterators, as in ArrayList, throw ConcurrentModificationException if the collection changes during iteration. Fail-safe iterators, as in CopyOnWriteArrayList, work on a snapshot and do not throw.

Q28. What are generics?

Type parameters such as List<String> that let the compiler check types and remove casts. They give type safety for collections and reusable code.

Q29. What is type erasure?

The compiler removes generic type information after checking it, so List<String> and List<Integer> are both List at runtime. That is why you cannot write new T().

Q30. What do ? extends T and ? super T mean?

? extends T accepts T or its subtypes and is for reading. ? super T accepts T or its supertypes and is for writing. The PECS rule: producer extends, consumer super.

Exceptions & Multithreading

Q31. What is the difference between checked and unchecked exceptions?

Checked exceptions such as IOException must be caught or declared with throws. Unchecked exceptions extend RuntimeException, such as NullPointerException, and need neither.

Q32. What is the difference between throw and throws?

throw raises an exception inside a method. throws in a method signature declares which checked exceptions it may raise.

Q33. What is try-with-resources?

A try statement that declares resources such as streams. Anything implementing AutoCloseable is closed automatically, even when an exception is thrown.

Q34. How do you create a thread in Java?

Extend Thread, implement Runnable or Callable, or better, submit tasks to an ExecutorService. Java 21 adds lightweight virtual threads through Thread.ofVirtual().

Q35. What is the difference between Runnable and Callable?

Runnable.run() returns nothing and cannot throw checked exceptions. Callable.call() returns a value and can throw them, and the result comes back as a Future.

Q36. What does synchronized do?

It lets only one thread at a time run a block or method on the same lock object, which prevents race conditions and makes changes visible to other threads.

Q37. What does volatile do?

It makes every read of a variable come from main memory, so all threads see the latest write. It does not make compound actions like count++ atomic.

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

Two or more threads each wait for a lock the other holds, forever. Prevent it by always taking locks in the same order, using timeouts with tryLock, or holding fewer locks.

Q39. What is the difference between wait() and sleep()?

wait() releases the object's lock and waits for notify(), and must be called inside synchronized. sleep() pauses the thread for a time and keeps any locks it holds.

Q40. What are virtual threads?

Lightweight threads managed by the JVM, final since Java 21. Millions can run at once, which lets simple blocking code scale like async code for I/O-heavy servers.

Java 8+ Features

Q41. What are lambda expressions?

Short anonymous functions such as (a, b) -> a + b that implement a functional interface. They make callbacks and stream operations concise.

Q42. What is a functional interface?

An interface with exactly one abstract method, such as Runnable, Predicate or Function. It can be marked @FunctionalInterface and implemented with a lambda.

Q43. What is the Stream API?

A way to process collections with chained operations such as filter, map and collect. Streams are lazy, do not change the source and can run in parallel.

Q44. What is the difference between intermediate and terminal stream operations?

Intermediate operations such as filter and map return a new stream and run lazily. Terminal operations such as collect, forEach and count start processing and produce a result.

Q45. What is the difference between map and flatMap?

map transforms each element into one result. flatMap transforms each element into a stream and flattens them, for example turning a list of lists into one list.

Q46. What is Optional?

A container that may or may not hold a value, used as a return type to avoid returning null. Use orElse, orElseThrow or ifPresent instead of calling get() directly.

Q47. What are method references?

Shorthand for lambdas that call an existing method, such as String::toUpperCase or System.out::println.

Q48. What are default methods in interfaces?

Methods with a body in an interface, marked default. They let interfaces gain new methods without breaking existing implementations.

Q49. What are records?

Compact classes such as record Point(int x, int y) {} that generate the constructor, accessors, equals, hashCode and toString. They are immutable data carriers.

Q50. What are sealed classes and pattern matching?

Sealed classes restrict which classes can extend them with permits. Pattern matching for instanceof and switch lets you test a type and bind a variable at once, and with sealed types the compiler checks that a switch covers every case.