Interview Prep | Java
Java Interview Questions

Entry, Mid, and Advanced Java questions with short answers (OOP, collections, exceptions, threads, JVM, streams). Use search to filter quickly.

🔍

Java Entry Level Q&A

Back to Top ↑
Q1. What are the main features of Java?
A. Object-oriented, platform-independent (bytecode + JVM), robust (GC), secure (sandboxing, strong typing), multithreaded, rich standard library, and great tooling/ecosystem.
Entry
Q2. What is the difference between JDK, JRE, and JVM?
A. JVM runs bytecode. JRE = JVM + standard libraries to run apps. JDK = JRE + compiler and dev tools to build apps.
Entry
Q3. What are the four pillars of OOP?
A. Encapsulation, inheritance, polymorphism, and abstraction.
Entry
Q4. What is a class vs object?
A. A class is a blueprint; an object is an instance created from a class.
Entry
Q5. What is the parent class of all classes in Java?
A. java.lang.Object.
Entry
Q6. Do interfaces extend java.lang.Object?
A. No. Interfaces do not extend Object, but any class that implements an interface still extends Object.
Entry
Q7. What is inheritance in Java?
A. A subclass reuses and extends behavior/state of a superclass using extends.
Entry
Q8. Does Java support multiple inheritance of classes?
A. No. A class cannot extend multiple classes. Use interfaces to achieve “multiple inheritance of type”.
Entry
Q9. How can Java implement multiple inheritance?
A. A class can implement multiple interfaces: class C implements A, B.
Entry
Q10. What is method overloading?
A. Same method name with different parameters (compile-time).
Entry
Q11. What is method overriding?
A. A subclass provides a new implementation with the same signature (runtime polymorphism).
Entry
Q12. What is compile-time vs runtime polymorphism?
A. Overloading is resolved at compile-time; overriding is resolved at runtime using dynamic dispatch.
Entry
Q13. What is the JVM?
A. Java Virtual Machine runs bytecode and provides GC, JIT compilation, and runtime services.
Entry
Q14. What is platform independence in Java?
A. Java compiles to bytecode. Any platform with a compatible JVM can run the same bytecode.
Entry
Q15. What is the latest version of Java?
A. Java releases frequently (roughly every 6 months). For production, many teams choose the latest LTS release and verify the current versions from Oracle/Adoptium release pages.
Entry
Q16. == vs equals()?
A. == compares references (identity). equals() compares logical equality (if implemented).
Entry
Q17. Why are Strings immutable in Java?
A. Immutability improves security, caching (string pool), thread-safety, and makes hashing stable for maps/sets.
Entry
Q18. String vs StringBuilder vs StringBuffer?
A. String is immutable. StringBuilder is mutable and fast (not thread-safe). StringBuffer is mutable and synchronized (thread-safe but slower).
Entry
Q19. What is an exception?
A. An error event that disrupts normal flow; handled with try/catch/finally.
Entry
Q20. Checked vs unchecked exceptions?
A. Checked exceptions must be caught/declared; unchecked exceptions (RuntimeException) do not have to be declared.
Entry
Q21. final vs finally vs finalize?
A. final: constant/non-overridable. finally: block after try/catch. finalize(): legacy GC hook; avoid in modern Java.
Entry
Q22. What is an interface?
A. A contract of members a class implements. Interfaces can have default/static methods (Java 8+).
Entry
Q23. abstract class vs interface?
A. Abstract class can hold state and constructors; interface defines a contract (plus default/static methods). A class can implement multiple interfaces but extend only one class.
Entry
Q24. What is the difference between this() and super()?
A. this() calls another constructor in the same class; super() calls a superclass constructor. Both must be the first statement in a constructor.
Entry
Q25. Are constructors inherited?
A. No. Constructors are not inherited, but superclass constructors run during subclass object creation.
Entry
Q26. What is constructor chaining?
A. Calling one constructor from another using this() or calling the parent constructor using super().
Entry
Q27. Can you create an object without using new?
A. Yes. Examples: reflection (Class.newInstance / Constructor.newInstance), cloning, deserialization, and factory methods.
Entry
Q28. What are access modifiers in Java?
A. private (class only), default/package-private (package), protected (package + subclasses), public (everywhere).
Entry
Q29. What are common non-access modifiers?
A. static, final, abstract, synchronized, transient, volatile, native, strictfp.
Entry
Q30. Can we overload main() method?
A. Yes, but the JVM entry point must be public static void main(String[] args).
Entry
Q31. Why must main() be public and static?
A. public so JVM can access it; static so JVM can invoke it without creating an instance.
Entry
Q32. What is type casting?
A. Converting a value/reference from one type to another. Primitive casting changes numeric type; reference casting changes the declared reference type.
Entry
Q33. What is auto-boxing and unboxing?
A. Auto-boxing wraps primitives into wrapper objects; unboxing extracts primitive values from wrappers.
Entry

Java Mid Level Q&A

Back to Top ↑
⚙️
Q1. ArrayList vs LinkedList?
A. ArrayList is fast for random access; LinkedList is slower for access and has higher overhead.
Mid
⚙️
Q2. HashSet vs TreeSet?
A. HashSet is typically faster (hash-based, unordered). TreeSet keeps elements sorted with O(log n) operations.
Mid
⚙️
Q3. HashMap vs TreeMap?
A. HashMap average O(1) operations unordered; TreeMap sorted with O(log n) operations.
Mid
⚙️
Q4. HashMap vs Hashtable?
A. Hashtable is legacy and synchronized; HashMap is newer and faster (not thread-safe). Prefer ConcurrentHashMap for concurrency.
Mid
⚙️
Q5. ConcurrentHashMap vs synchronizedMap?
A. ConcurrentHashMap scales better with fine-grained concurrency; synchronizedMap uses one lock and can become a bottleneck.
Mid
⚙️
Q6. equals() and hashCode() contract?
A. If equals() is true for two objects, their hashCode() must be the same.
Mid
⚙️
Q7. Why override hashCode() when overriding equals()?
A. Hash-based collections use hashCode() to locate buckets. If equal objects have different hashes, lookups break.
Mid
⚙️
Q8. Checked vs unchecked exceptions?
A. Checked must be declared/caught; unchecked (RuntimeException) do not.
Mid
⚙️
Q9. What is garbage collection?
A. The JVM automatically frees memory of unreachable objects using GC algorithms.
Mid
⚙️
Q10. Stack vs heap memory?
A. Stack holds method frames and local variables; heap holds objects/arrays. Stack is per-thread; heap is shared.
Mid
⚙️
Q11. What is immutability?
A. An objects state cannot change after creation (e.g., String). Improves safety and concurrency.
Mid
⚙️
Q12. What is a package?
A. A namespace for organizing classes and preventing naming conflicts.
Mid
⚙️
Q13. final vs finally vs finalize?
A. final: constant/non-overridable; finally: block after try/catch; finalize(): legacy GC hook (avoid).
Mid
⚙️
Q14. What is a static initializer vs instance initializer?
A. Static initializer runs when the class loads; instance initializer runs each time an object is created (before the constructor body).
Mid
⚙️
Q15. What is ClassCastException?
A. A runtime exception when you cast an object to an incompatible type. Often avoided with instanceof checks or proper generics.
Mid
⚙️
Q16. What is the difference between overloading and overriding?
A. Overloading: same name, different params (compile-time). Overriding: same signature in subclass (runtime).
Mid
⚙️
Q17. Can we override static methods?
A. No. Static methods are hidden, not overridden.
Mid
⚙️
Q18. What is the difference between String literals and new String()?
A. Literals can be interned in the string pool; new String() always creates a new object (unless interned explicitly).
Mid
⚙️
Q19. What is the difference between fail-fast and fail-safe iterators?
A. Fail-fast throws ConcurrentModificationException on structural changes; fail-safe iterates over a snapshot/copy (common in concurrent collections).
Mid
⚙️
Q20. What is try-with-resources?
A. A try block that automatically closes resources implementing AutoCloseable (prevents leaks).
Mid
⚙️
Q21. What is a functional interface?
A. An interface with exactly one abstract method, usable with lambdas (e.g., Runnable, Comparator).
Mid
⚙️
Q22. map() vs flatMap() in Streams?
A. map transforms each element; flatMap transforms and flattens nested streams into one.
Mid
⚙️
Q23. Optional: when to use it?
A. Use Optional as a return type to represent “may be missing”. Avoid storing Optional as fields in most cases.
Mid
⚙️
Q24. What is serialization and deserialization?
A. Serialization converts an object to bytes for storage/transfer; deserialization rebuilds it. Manage serialVersionUID and security carefully.
Mid
⚙️
Q25. What is the difference between composition and inheritance?
A. Inheritance is “is-a”; composition is “has-a”. Prefer composition for flexibility and lower coupling.
Mid

Java Advanced Level Q&A

Back to Top ↑
🚀
Q1. synchronized vs Lock?
A. synchronized uses intrinsic monitors; Lock offers tryLock, fairness, and multiple conditions.
Advanced
🚀
Q2. wait() vs sleep()?
A. sleep pauses a thread for time; wait releases the monitor and waits for notify/notifyAll (used for coordination).
Advanced
🚀
Q3. notify() vs notifyAll()?
A. notify wakes one waiting thread; notifyAll wakes all waiting threads (safer when multiple conditions exist).
Advanced
🚀
Q4. What is deadlock and how to prevent it?
A. Circular waiting on locks. Prevent via lock ordering, timeouts, and minimizing lock scope.
Advanced
🚀
Q5. What is volatile?
A. Ensures visibility of updates across threads (but does not make compound actions atomic).
Advanced
🚀
Q6. What is the Java Memory Model?
A. Defines visibility and ordering of reads/writes across threads and the happens-before rules.
Advanced
🚀
Q7. What is a thread pool?
A. A managed set of reusable threads to run tasks efficiently (ExecutorService).
Advanced
🚀
Q8. Runnable vs Callable?
A. Runnable returns no result and can’t throw checked exceptions; Callable returns a result and can throw exceptions (via Future).
Advanced
🚀
Q9. Future vs CompletableFuture?
A. Future is basic async result; CompletableFuture supports chaining, composition, and callbacks.
Advanced
🚀
Q10. ConcurrentHashMap vs HashMap?
A. ConcurrentHashMap supports safe concurrent access with better scalability than synchronized maps.
Advanced
🚀
Q11. What is lock contention and how to reduce it?
A. Many threads compete for the same lock. Reduce by minimizing critical sections, using concurrent data structures, and avoiding unnecessary shared state.
Advanced
🚀
Q12. What is a race condition?
A. When correctness depends on timing/order of threads. Fix using synchronization, immutability, atomic classes, or confinement.
Advanced
🚀
Q13. What is GC tuning?
A. Adjusting heap sizes and GC algorithms to balance throughput vs latency.
Advanced
🚀
Q14. What is stop-the-world in GC?
A. A pause where application threads stop so the JVM can safely perform certain GC phases.
Advanced
🚀
Q15. What is memory leak in Java (with GC)?
A. Holding references to unused objects prevents GC (e.g., static collections, listener leaks, caches without eviction).
Advanced
🚀
Q16. ClassNotFoundException vs NoClassDefFoundError?
A. ClassNotFoundException is checked and occurs when loading a class dynamically fails; NoClassDefFoundError happens when the class was present at compile-time but missing at runtime.
Advanced
🚀
Q17. What is class loading (high level)?
A. The JVM loads classes via class loaders, verifies, links, and initializes them. Custom class loaders can change how classes are found.
Advanced
🚀
Q18. What is reflection and when to avoid it?
A. Reflection inspects/invokes members at runtime. It is powerful but slower, less safe, and can break encapsulation; use sparingly.
Advanced
🚀
Q19. What is dependency injection (DI) and why use it?
A. DI provides dependencies from outside the class (constructor injection). It improves testability and reduces coupling.
Advanced
🚀
Q20. Functional interfaces and lambdas?
A. A functional interface has one abstract method; lambdas provide inline implementations.
Advanced
🚀
Q21. What is Stream laziness?
A. Intermediate operations are lazy and run only when a terminal operation executes. This enables optimization and short-circuiting.
Advanced
🚀
Q22. What is short-circuiting in Streams?
A. Operations like findFirst/anyMatch can stop early without processing all elements.
Advanced
🚀
Q23. What is Big-O difference: HashMap vs TreeMap?
A. HashMap: average O(1) get/put; TreeMap: O(log n) but sorted and supports range queries.
Advanced
🚀
Q24. Explain happens-before in simple terms.
A. It’s a rule that guarantees visibility/order: if A happens-before B, then B sees A’s writes (e.g., locking, volatile, thread start/join).
Advanced