Guides › Interviews
Top 50 Java Interview Questions for Freshers (with Answers)
JVM, strings, OOP, exceptions, collections, HashMap internals, multithreading and Java 8 — the 50 Java questions asked most, each with a short answer.
These are the Java questions freshers are asked most in campus and off-campus interviews — from JVM basics to collections, exceptions, multithreading and Java 8. Each answer is short enough to say out loud in an interview. For deeper explanations, follow the links to the notes.
Basics and the JVM
1. What are JDK, JRE and JVM?
The JVM runs bytecode. The JRE = JVM + core libraries (enough to run programs). The JDK = JRE + development tools like javac (needed to write programs). See JDK, JRE, JVM and Java Memory.
2. Why is Java platform independent?
javac compiles source to bytecode, not machine code. Any device with a JVM can run that bytecode — "write once, run anywhere". The JVM itself is platform specific.
3. Is Java 100% object oriented?
No — it has primitive types (int, char, boolean…) that are not objects. Wrapper classes (Integer, Character) exist for when objects are needed.
4. What is the difference between == and .equals()?
== compares references for objects (are they the same object?). .equals() compares contents when the class overrides it (like String).
5. Why is main public static void?
public so the JVM can call it from outside, static so it can run without creating an object, void because it returns nothing to the JVM.
6. What are the primitive types and their sizes?
byte 1, short 2, int 4, long 8, float 4, double 8, char 2 (UTF-16), boolean (JVM dependent).
7. What is autoboxing?
Automatic conversion between primitives and wrappers: Integer x = 5; (boxing), int y = x; (unboxing). Beware: Integer values between −128 and 127 are cached, so == may work there and fail for larger values.
8. What are stack and heap memory? Each thread has a stack holding method frames and local variables. Objects live on the shared heap, managed by the garbage collector.
9. What is garbage collection?
The JVM automatically frees objects that are no longer reachable from any live reference. You can suggest it with System.gc(), but not force it.
10. What does final mean on a variable, method and class?
Variable: can't be reassigned. Method: can't be overridden. Class: can't be extended (e.g. String).
Strings
11. Why are Strings immutable?
For security (class names, URLs, passwords can't be changed after checks), thread safety, and the String pool — shared literals are only safe if they can't change. It also lets String cache its hash code.
12. What is the String pool?
A special area where string literals are stored once and reused. String a = "hi"; String b = "hi"; → same object. new String("hi") creates a separate object.
13. String vs StringBuilder vs StringBuffer?
String is immutable. StringBuilder is mutable and fast (not synchronized). StringBuffer is mutable and synchronized (thread-safe, slower). Use StringBuilder for building strings in loops. See String, StringBuilder and StringBuffer.
14. How many objects does new String("abc") create?
Up to two: one in the pool for the literal "abc" (if not already there) and one on the heap for new.
OOP in Java
15. What are the four pillars of OOP? Encapsulation, abstraction, inheritance and polymorphism. See Four Pillars of OOP.
16. Overloading vs overriding? Overloading: same method name, different parameters, decided at compile time. Overriding: a subclass redefines a parent method with the same signature, decided at runtime.
17. Can we override a static or private method? No. Static methods are hidden, not overridden (resolved by reference type). Private methods aren't visible to subclasses.
18. Abstract class vs interface? An abstract class can have state, constructors and concrete methods; a class extends only one. An interface is a contract (plus default/static methods since Java 8); a class can implement many. See Abstract Class vs Interface.
19. Why doesn't Java support multiple inheritance of classes? To avoid the diamond problem — ambiguity when two parents have the same method. Multiple inheritance of type is allowed through interfaces.
20. What are this and super?
this refers to the current object (and this() calls another constructor). super refers to the parent (and super() calls the parent constructor; it must be the first statement).
21. Can a constructor be private? Yes — used for Singleton and utility classes so no one else can create objects.
22. What is a static block?
Code that runs once when the class is loaded, before main — used to initialise static data.
23. What are access modifiers?
private (class only), default (package), protected (package + subclasses), public (everywhere). See Classes, Objects, Constructors and Access Modifiers.
24. Why override hashCode() when overriding equals()?
Hash-based collections (HashMap, HashSet) first use hashCode() to find the bucket. Equal objects must have equal hash codes, or lookups fail.
Exceptions
25. Checked vs unchecked exceptions?
Checked exceptions (e.g. IOException) must be caught or declared with throws — checked at compile time. Unchecked ones (RuntimeException subclasses like NullPointerException) are not enforced. See Exception Handling in Java.
26. throw vs throws?
throw actually throws an exception object. throws in a method signature declares that the method may throw it.
27. Does finally always run?
Almost always — even after return. It doesn't run if the JVM exits (System.exit) or crashes.
28. Error vs Exception?
Error (e.g. OutOfMemoryError, StackOverflowError) means serious JVM problems you shouldn't catch. Exception covers conditions a program can handle.
29. What is try-with-resources?
try (BufferedReader r = …) { } — resources implementing AutoCloseable are closed automatically, even on exceptions.
Collections
30. ArrayList vs LinkedList?
ArrayList: dynamic array, O(1) random access, slow inserts in the middle. LinkedList: doubly linked list, O(1) insert/remove at ends with an iterator, O(n) access by index. ArrayList is the usual default. See Java Collections Framework.
31. How does HashMap work internally? Keys are hashed to a bucket index in an array. Collisions are stored in a linked list per bucket, converted to a red-black tree when a bucket gets large (Java 8+). When the size exceeds capacity × load factor (0.75), the table doubles and entries are rehashed. Average get/put is O(1).
32. HashMap vs Hashtable vs ConcurrentHashMap?
HashMap: not synchronized, allows one null key. Hashtable: legacy, fully synchronized, no nulls. ConcurrentHashMap: thread-safe with fine-grained locking — use it for concurrency.
33. HashSet vs TreeSet vs LinkedHashSet?
HashSet: no order, O(1). LinkedHashSet: keeps insertion order. TreeSet: sorted, O(log n).
34. Comparable vs Comparator?
Comparable (compareTo) defines the class's natural order inside the class. Comparator (compare) defines extra orders outside it, e.g. list.sort(Comparator.comparing(Student::getMarks)).
35. Fail-fast vs fail-safe iterators?
Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is modified during iteration. Fail-safe ones (CopyOnWriteArrayList, ConcurrentHashMap) work on a copy/snapshot and don't throw.
36. How do you remove elements while iterating?
Use iterator.remove() or list.removeIf(x -> …) — not list.remove() inside a for-each loop.
Multithreading
37. Two ways to create a thread?
Extend Thread, or implement Runnable (preferred — you can still extend another class). Modern code uses an ExecutorService. See Multithreading in Java.
38. start() vs run()?
start() creates a new thread that then calls run(). Calling run() directly just runs it on the current thread.
39. What does synchronized do?
Only one thread at a time can run a synchronized method/block on the same lock object — prevents race conditions.
40. What is volatile?
Guarantees that reads and writes of a variable go to main memory, so all threads see the latest value. It does not make count++ atomic — use AtomicInteger for that.
41. wait() vs sleep()?
wait() (Object method) releases the lock and waits for notify(); must be called inside synchronized code. sleep() (Thread method) pauses without releasing locks.
42. What is a deadlock and how to avoid it?
Threads waiting for each other's locks forever. Avoid it by always acquiring locks in the same order, using tryLock with timeouts, and holding locks briefly. See Deadlocks.
Java 8 and later
43. What is a lambda expression?
A short way to implement a functional interface: (a, b) -> a + b. See Java 8 Features.
44. What is a functional interface?
An interface with exactly one abstract method, e.g. Runnable, Comparator, Function, Predicate. Marked with @FunctionalInterface.
45. What is the Stream API?
A way to process collections declaratively: list.stream().filter(x -> x > 10).map(x -> x * 2).collect(Collectors.toList()). Streams are lazy and don't modify the source.
46. map vs flatMap?
map transforms each element into one element. flatMap transforms each into a stream and flattens them — e.g. a list of lists into one list.
47. What is Optional?
A container that may or may not hold a value — avoids returning null: findUser(id).orElse(defaultUser).
48. What are default methods in interfaces? Methods with a body in an interface (Java 8) — lets libraries add methods without breaking existing implementations.
Miscellaneous
49. What is serialization?
Converting an object to a byte stream (to save or send it). The class implements Serializable; transient fields are skipped.
50. Shallow copy vs deep copy? A shallow copy copies field values, so nested objects are shared. A deep copy also copies the nested objects, so the copies are fully independent.
How to use this list
- Read each answer, then close the page and say it in your own words.
- Revise the linked notes for any answer you couldn't explain.
- Test yourself with Java interview questions and flashcards.
- Do a technical mock interview on Java to practise saying it under pressure.
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.