Top Java Interview Questions for Freshers (With Answers and Code)
The most asked Java interview questions for freshers with clear answers and code: JDK vs JRE, == vs equals, String immutability, OOP, collections, HashMap internals, exceptions, threads and Java 8.
Java interviews for freshers focus on fundamentals: how the language works, OOP, collections, exceptions and a little concurrency. This list covers the questions that come up again and again, with answers short enough to say out loud and code you can write on a whiteboard.
Topics to prepare#
Core Java#
1. What is the difference between JDK, JRE and JVM?#
The JVM runs bytecode. The JRE is the JVM plus standard libraries, enough to run programs. The JDK is the JRE plus development tools like javac. Full details in JVM vs JDK vs JRE explained.
2. Why is Java platform independent?#
javac compiles source into bytecode, not machine code. Any operating system with a JVM can run that bytecode, so the same .class file runs everywhere. Java itself is platform independent; the JVM is not.
3. What is the difference between == and equals()?#
String a = new String("java");
String b = new String("java");
System.out.println(a == b); // false: different objects
System.out.println(a.equals(b)); // true: same content== compares references (memory addresses) for objects. equals() compares content, if the class overrides it.
4. Why are Strings immutable?#
- String pool: literals are shared, so changing one would change it everywhere.
- Security: file paths, URLs and class names can't be altered after a check.
- Thread safety: immutable objects can be shared freely between threads.
- Caching hashCode: makes Strings fast as
HashMapkeys.
5. String vs StringBuilder vs StringBuffer?#
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread-safe | Yes (immutable) | No | Yes (synchronized) |
| Speed | Slow when concatenating in loops | Fastest | Slower than StringBuilder |
6. What does static mean?#
A static member belongs to the class, not to any object. There is one copy shared by all instances, and you can access it without creating an object. That's why main is static: the JVM calls it before any object exists.
7. final, finally and finalize?#
final makes a variable constant, a method non-overridable, or a class non-extendable. finally is a block that always runs after try/catch. finalize() was a GC cleanup hook; it's deprecated and you shouldn't use it.
OOP#
8. What are the four pillars of OOP?#
Encapsulation, inheritance, polymorphism and abstraction. Our OOP concepts guide covers each with examples.
9. Overloading vs overriding?#
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // overloading: same name, different params
}
class Animal { String sound() { return "..."; } }
class Dog extends Animal {
@Override
String sound() { return "Woof"; } // overriding: same signature in subclass
}Overloading is resolved at compile time; overriding is resolved at runtime (dynamic dispatch).
10. Abstract class vs interface?#
| Abstract class | Interface | |
|---|---|---|
| Inheritance | A class extends only one | A class can implement many |
| State | Can have instance fields | Only constants |
| Constructors | Yes | No |
| Methods | Abstract and concrete | Abstract, default, static, private |
| Use when | Classes share code and state ("is-a") | Unrelated classes share a capability ("can-do") |
11. Why doesn't Java support multiple inheritance of classes?#
To avoid the diamond problem: if two parents define the same method, which one does the child inherit? Java allows multiple interfaces instead, and if two default methods clash, the class must override and choose explicitly.
Collections#
12. ArrayList vs LinkedList?#
ArrayList is backed by an array: O(1) random access, slow inserts in the middle. LinkedList is a doubly linked list: O(1) insert at known nodes, O(n) access by index. In practice, ArrayList is faster for almost everything thanks to CPU caching.
13. How does HashMap work internally?#
put(key, value)callskey.hashCode()and spreads the bits.- The hash picks a bucket index in an internal array.
- Entries in the same bucket form a linked list; since Java 8, a bucket with more than 8 entries becomes a red-black tree.
equals()finds the exact key within the bucket.- When size exceeds capacity × 0.75 (load factor), the array doubles and entries are rehashed.
14. Why must you override hashCode() when you override equals()?#
Equal objects must have equal hash codes. If they don't, a HashMap may look in the wrong bucket and fail to find a key that's "equal".
record Point(int x, int y) {} // records generate equals and hashCode for you15. HashMap vs Hashtable vs ConcurrentHashMap?#
HashMap isn't thread-safe and allows one null key. Hashtable is synchronized on every method (legacy, slow). ConcurrentHashMap is thread-safe with fine-grained locking and doesn't allow nulls. See the collections guide.
16. Fail-fast vs fail-safe iterators?#
Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection changes during iteration. Fail-safe iterators (CopyOnWriteArrayList, ConcurrentHashMap) work on a copy or snapshot and don't throw.
Exceptions#
17. Checked vs unchecked exceptions?#
Checked exceptions (IOException) must be caught or declared. Unchecked exceptions (RuntimeException subclasses like NullPointerException) don't. More in Java exception handling.
18. Does finally always run?#
Almost always: even after return. It doesn't run if the JVM exits (System.exit()), crashes, or the thread is killed.
Multithreading#
19. start() vs run()?#
start() creates a new thread that calls run(). Calling run() directly just runs it on the current thread.
20. What is volatile?#
It guarantees that a write by one thread is visible to other threads. It does not make compound operations like count++ atomic. See the multithreading guide.
Java 8 and beyond#
21. What's new in Java 8?#
Lambdas, functional interfaces, the Stream API, Optional, default methods in interfaces and the new java.time date API.
List<String> names = List.of("asha", "ravi", "meera", "arjun");
List<String> result = names.stream()
.filter(n -> n.startsWith("a"))
.map(String::toUpperCase)
.sorted()
.toList(); // [ARJUN, ASHA]22. What is a functional interface?#
An interface with exactly one abstract method, like Runnable, Comparator or Function<T, R>. Lambdas implement functional interfaces.
23. What is Optional for?#
It makes "might be missing" explicit in a method's return type, which pushes callers to handle the empty case instead of hitting NullPointerException.
String city = userRepo.findById(id)
.map(User::getCity)
.orElse("Unknown");Coding questions to practise#
- Reverse a string without
StringBuilder.reverse(). - Check if a string is a palindrome.
- Find duplicates in an array using a
HashSet. - Count character frequency with a
HashMap. - Find the second largest number in an array in one pass.
- FizzBuzz, Fibonacci (iterative and recursive) and factorial.
Interviewers care about how you think. Say your approach out loud, mention the time complexity, and test your code with an edge case like an empty array or null input before you say "done". Brush up with Big O notation explained.
Key takeaways#
- Know the JDK/JRE/JVM split and why bytecode makes Java portable.
- Be ready to explain
==vsequals(), String immutability and theequals/hashCodecontract. - Understand HashMap internals, ArrayList vs LinkedList and fail-fast iterators.
- Cover exceptions, thread basics and Java 8 features like streams and Optional.
- Practise small coding problems and always state complexity and edge cases.