These Java interview questions are tailored for Freshers as well as Experienced developers to help you stand out in your next technical interview. We have added deep explanations, real-world examples, and best practices.
1. What are the key principles of OOPs and how does Java implement them?
Java follows four core OOPs principles:
- Encapsulation: Use private variables with public getters/setters.
- Inheritance: Code reuse via the
extends
keyword. - Polymorphism: Achieved through method overloading and overriding.
- Abstraction: Via abstract classes and interfaces.
abstract class Employee {
abstract double calculateSalary();
}
class Developer extends Employee {
double calculateSalary() { return 60000; }
}
2. How does HashMap work internally in Java?
HashMap is an efficient key-value data structure. Here’s how it works:
- Backed by an array of buckets (Node<K,V>[]).
- Key’s
hashCode()
determines the bucket index. - Collisions are handled via LinkedList or Tree (for large chains).
- One
null
key is allowed, multiple null values. - Resize triggers when size exceeds
capacity * loadFactor
.
3. Difference between == and equals() in Java?
==
compares references, while equals()
checks logical equality.
String a = new String("Test");
String b = new String("Test");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
4. Abstract class vs. Interface in Java?
Feature | Abstract Class | Interface |
---|---|---|
Method Types | Abstract + concrete | Abstract, default (since Java 8) |
Multiple Inheritance | No | Yes |
Constructors | Allowed | Not allowed |
5. Method overloading vs. overriding?
- Overloading: Same method name, different parameters (compile time).
- Overriding: Subclass redefines method (runtime).
6. Use of final keyword in Java?
- final variable: Cannot be reassigned.
- final method: Cannot be overridden.
- final class: Cannot be extended (e.g., String).
7. Checked vs. Unchecked exceptions?
- Checked: Must be handled (e.g., IOException).
- Unchecked: Runtime errors (e.g., NullPointerException).
8. What is the Java Memory Model?
Defines rules for visibility and ordering of variables accessed by threads. Includes:
volatile
for visibilitysynchronized
for atomicity and ordering
9. What are ClassLoaders in Java?
Responsible for dynamically loading classes:
- Bootstrap
- Extension
- Application
10. ArrayList vs. LinkedList?
Feature | ArrayList | LinkedList |
---|---|---|
Access Time | Fast (O(1)) | Slow (O(n)) |
Insertion | Slow (shifts elements) | Fast (pointer change) |
11. What is synchronization in Java?
Ensures that only one thread accesses critical section at a time:
synchronized void update() {
// thread-safe code
}
12. Thread-safe collections?
- Legacy: Vector, Hashtable
- Modern: ConcurrentHashMap, CopyOnWriteArrayList
13. Use of volatile keyword?
Ensures visibility of variable updates across threads.
volatile boolean running = true;
14. String vs. StringBuilder vs. StringBuffer?
- String: Immutable
- StringBuilder: Mutable, not thread-safe
- StringBuffer: Mutable, thread-safe
15. Memory leaks despite GC?
- Unreleased listeners
- Static references
- Improper cache use
16. What is transient keyword?
Prevents fields from being serialized:
transient int password;
17. Use of Optional in Java 8+
Optional name = Optional.ofNullable(user.getName());
name.ifPresent(System.out::println);
18. Callable vs. Runnable?
Runnable
: No return, no checked exceptions.Callable
: Returns a result, throws exceptions.
19. What is a deadlock?
Occurs when threads wait on each other’s locks indefinitely.
Avoid using:
- Lock ordering
- Try-lock with timeout
- Avoiding nested locks
20. Stream API usage?
list.stream()
.filter(s -> s.startsWith("A"))
.collect(Collectors.toList());
21. Functional programming in Java?
- Lambda expressions
- Method references
- Streams
- Functional interfaces
22. Comparator vs. Comparable?
Collections.sort(list, (a, b) -> b.age - a.age);
23. Fork/Join Framework?
Breaks tasks into smaller subtasks:
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new MyTask());
24. What is a happens-before relationship?
volatile write → volatile read
Thread.start() → run()
synchronized unlock → lock
25. What is try-with-resources?
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
br.readLine();
}
Closes resources automatically. Cleaner exception handling.
Take a pause here, revise previous 25 java interview questions. Make a summary of those in your mind then practice next 25 java interview questions.
26. What is the difference between heap and stack memory in Java?
- Stack: Stores method calls and local variables. Follows LIFO.
- Heap: Stores objects and instance variables. Managed by GC.
27. What are the different memory areas allocated by JVM?
- Method Area
- Heap
- Java Stack
- PC Registers
- Native Method Stack
28. How does Garbage Collection work in Java?
GC automatically deallocates unreachable objects. Major GC algorithms:
- Serial GC
- Parallel GC
- G1 GC
- ZGC (from Java 11)
29. What is a WeakReference in Java?
Used when objects should be garbage collected if no strong references exist:
WeakReference ref = new WeakReference<>(new MyObject());
30. What is the difference between fail-fast and fail-safe iterators?
- Fail-fast: Throws
ConcurrentModificationException
(e.g., ArrayList). - Fail-safe: Uses copy-on-write, no exceptions (e.g., CopyOnWriteArrayList).
31. What is the use of Enum in Java?
Enum provides type-safe constants and can have fields, methods, and constructors.
enum Status {
SUCCESS, FAILURE;
}
32. What is the difference between static and default methods in interfaces?
- default: Instance-level, can be overridden.
- static: Class-level, accessed via interface name.
33. What is the diamond problem and how does Java resolve it?
Occurs in multiple inheritance. Java resolves it using interfaces and method resolution rules.
34. How does Java 8 handle multiple inheritance?
Uses interfaces with default methods. Compiler resolves conflicts with explicit overriding.
35. Difference between Predicate and Function in Java?
Predicate<T>
: Returns boolean.Function<T, R>
: Transforms input of type T to output R.
36. What is the purpose of method reference (::) in Java?
Simplifies lambda expressions. Example:
list.forEach(System.out::println);
37. What is the role of the ForkJoinPool in parallel streams?
Handles multithreaded execution behind parallel streams for better performance.
38. What is immutability and how do you create an immutable class?
- Make class
final
- Make fields
private final
- No setters
- Return copies of mutable fields
39. What is the use of marker interfaces?
Marker interfaces like Serializable
provide metadata to the JVM or libraries.
40. What is a memory leak and how can you prevent it?
Occurs when objects are no longer used but not garbage collected.
- Avoid static references to heavy objects.
- Use WeakHashMap for caches.
41. Difference between HashSet, TreeSet, LinkedHashSet?
Type | Ordering | Performance |
---|---|---|
HashSet | Unordered | Fastest |
LinkedHashSet | Insertion Order | Medium |
TreeSet | Sorted Order | Slowest |
42. Explain method hiding in Java?
If a subclass defines a static method with the same name as in the parent, it hides the method, it does not override it.
43. Difference between deep copy and shallow copy?
- Shallow Copy: Copies reference
- Deep Copy: Clones entire object graph
44. What is the Singleton design pattern?
Ensures only one instance exists.
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
45. What are method references and where are they used?
Class::staticMethod
obj::instanceMethod
- Used with streams, lambdas
46. What is Optional and how is it better than null?
Prevents NullPointerException
by providing safe access:
Optional.ofNullable(obj).orElse("Default");
47. What is the difference between Collection and Collections?
- Collection: Interface for data structures.
- Collections: Utility class with static methods (sort, reverse, etc).
48. What is the difference between wait(), sleep(), and yield()?
wait()
: Releases lock, waits to be notified.sleep()
: Pauses thread, retains lock.yield()
: Hints scheduler to give up CPU.
49. Why is String immutable in Java?
Security, caching, thread-safety, and ClassLoader reliability.
50. How do you create a thread-safe singleton?
class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}
Pro Tip: Bookmark this list or download the PDF version for offline preparation (available on this site — for now do ctrl+p to download and save in PDF format).
Keep visiting IT Free Source for more such content and please feel free to ask your Java Interview Questions in comment section and we’ll provide an approach to answer it in the interviews to ace it.
If you are a fresher then aptitude is an essential part of your preparation which is required for almost all the examinations like E-Litmus, Amcat, TCS NQT, Wipro’s Elite Talent Hunt etc. You may follow This Aptitude series for learning most of the important topics which will help you land the job as a fresher. Even if you are a senior and wants to get better at programming then we know Maths is an important factor for a good coder, then do have a look at some of the imp topics you may like.