The top 40 Java interview questions for freshers in 2026 cluster into seven buckets: OOP four pillars (30%), Java fundamentals (JDK/JRE/JVM, data types) (15%), String handling and immutability (10%), Collections framework (15%), exception handling (8%), multithreading basics (8%), and JDBC/SQL basics (7%). Most fresher rounds at TCS NQT, Infosys InfyTQ, Cognizant GenC, and Accenture include 10–12 Java MCQs and 1–2 live coding questions on HackerRank. This guide gives all 40 with answers and 12 working Java code examples.
Table of Contents
- Java Topic Weightage in 2026 Fresher Interviews
- Company Round Formats (TCS / Infosys / Accenture)
- Java Fundamentals (Q1–Q7)
- OOP Concepts in Java (Q8–Q18)
- String Handling (Q19–Q22)
- Collections Framework (Q23–Q30)
- Exception Handling (Q31–Q34)
- Multithreading (Q35–Q37)
- JDBC & Coding Patterns (Q38–Q40)
- 4-Week Java Interview Prep Plan
Java Topic Weightage in 2026 Fresher Interviews
| Topic Cluster | Frequency in MCQ | Frequency in Coding |
|---|---|---|
| OOP four pillars (encapsulation, inheritance, polymorphism, abstraction) | 30% | 25% |
| Java fundamentals (JDK/JRE/JVM, data types, operators) | 15% | 10% |
| Collections framework (ArrayList, HashMap, HashSet) | 15% | 20% |
| String handling and immutability | 10% | 15% |
| Exception handling (try/catch/finally, checked vs unchecked) | 8% | 10% |
| Multithreading basics (Thread, Runnable, synchronized) | 8% | 10% |
| JDBC / SQL basics | 7% | 5% |
| Coding patterns (reverse linked list, two-sum, balanced parens) | — | 10% |
Trend in 2026: Collections questions (especially HashMap internals — bucketing, collision, equals/hashCode) have grown from 8% in 2024 to ~15% in 2026, reflecting the shift from pure-OOP interviews to production-readiness filtering.
Company Round Formats: TCS NQT, Infosys InfyTQ, Accenture
| Company Round | Java Format | Difficulty |
|---|---|---|
| TCS NQT (2026) | 10–12 Java MCQs + 1–2 coding (HackerRank) | Easy to medium (OOP output tracing + 1 DSA) |
| Infosys InfyTQ (2026) | 10 Java MCQs + 1 coding | Easy to medium (String + Collections) |
| Infosys HackWithInfy (2026) | DSA round | Medium to hard (LeetCode medium) |
| Wipro NLTH (2026) | 8–10 Java MCQs | Easy only |
| Accenture (2026) | 12 Java MCQs + 1 coding | Easy to medium |
| Cognizant GenC (2026) | 10–12 Java MCQs + 1 coding | Easy to medium |
| Product companies (Flipkart, Razorpay) | 2–3 Java live-coding rounds | Medium to hard (Collections + Multithreading) |
Java Fundamentals (Q1–Q7)
Q1. What is the difference between JDK, JRE, and JVM?
JVM (Java Virtual Machine) is the runtime that executes Java bytecode — platform-specific but interprets the same .class files everywhere. JRE (Java Runtime Environment) is JVM + standard libraries needed to RUN Java applications. JDK (Java Development Kit) is JRE + compiler (javac) + debuggers + tools needed to DEVELOP Java applications. Install JDK to develop; install JRE (now bundled with JDK) to run.
Q2. Is Java pass-by-value or pass-by-reference?
Java is strictly pass-by-value — always. For primitive arguments, the value is copied. For object arguments, the reference (the pointer to the object) is copied — so the called method can mutate the object's fields but cannot reassign the caller's reference. A common interview trap: "swap two integers in a method" — the caller's variables don't swap because the references were copied.
Q3. What is the difference between == and .equals() in Java?
== compares primitive values OR reference identity (whether two references point to the same object). .equals() compares object content (defined per class; Object.equals defaults to ==, but String, Integer, etc. override it). For strings: use .equals() for content comparison. "hello" == new String("hello") is false (different objects); "hello".equals(new String("hello")) is true.
Q4. What is the difference between int, Integer, and String?
int is a primitive (32-bit, no methods, default 0, faster). Integer is the wrapper class (object, has methods like parseInt, default null, can be used in generics). Java auto-boxes between them. String is an immutable character sequence — not a number primitive or wrapper.
Q5. What is autoboxing and unboxing?
// autoboxing: int → Integer automatically
List<Integer> numbers = new ArrayList<>();
numbers.add(5); // int 5 auto-boxed to Integer.valueOf(5)
// unboxing: Integer → int automatically
int first = numbers.get(0); // Integer auto-unboxed to int
// Watch out: null Integer unboxing throws NullPointerException
Integer nullVal = null;
int x = nullVal; // NullPointerException at runtimeQ6. What are the Java primitive data types?
| Type | Size | Range | Default |
|---|---|---|---|
byte | 8-bit | -128 to 127 | 0 |
short | 16-bit | -32,768 to 32,767 | 0 |
int | 32-bit | -2³¹ to 2³¹-1 | 0 |
long | 64-bit | -2⁶³ to 2⁶³-1 | 0L |
float | 32-bit | ~±3.4e38, 7-digit precision | 0.0f |
double | 64-bit | ~±1.8e308, 15-digit precision | 0.0d |
char | 16-bit | 0 to 65,535 (Unicode) | '\u0000' |
boolean | 1-bit (JVM-dependent) | true / false | false |
Q7. What is the difference between final, finally, and finalize?
final — keyword: a final variable cannot be reassigned, a final method cannot be overridden, a final class cannot be subclassed. finally — block: code in a finally block runs after try/catch, used for cleanup (closing files, releasing locks). finalize — method (deprecated since Java 9): called by GC before reclaiming an object — unreliable, never use for resource cleanup.
OOP Concepts in Java (Q8–Q18)
Q8. What are the four pillars of OOP?
Encapsulation — bundling data + methods, hiding internals via access modifiers (private/public/protected) and exposing a public API via getters/setters. Abstraction — hiding implementation details, exposing only the interface (abstract classes, interfaces). Inheritance — extending a parent class to reuse code (extends keyword). Polymorphism — one interface, many implementations (method overloading for compile-time, overriding for runtime).
Q9. What is the difference between abstract class and interface?
| Feature | Abstract class | Interface |
|---|---|---|
| Methods | Abstract + concrete | Abstract (Java 7); default + static allowed (Java 8+); private allowed (Java 9+) |
| Fields | Any (instance + static) | Only public static final constants |
| Inheritance | Single (extends) | Multiple (implements) |
| Constructor | Yes | No |
| Use when | Shared state + partial implementation | Contract only / capability ("can-do") |
Q10. What is method overloading vs overriding?
Overloading (compile-time polymorphism): same method name, different parameter list (number, type, or order) in the SAME class. Return type can differ but parameter list must. Overriding (runtime polymorphism): subclass provides a different implementation for a method already defined in the parent class. Same name, same parameters. Use @Override annotation; access modifier cannot be more restrictive.
class Calculator {
int add(int a, int b) { return a + b; } // overload 1
double add(double a, double b) { return a + b; } // overload 2 (different type)
int add(int a, int b, int c) { return a + b + c; } // overload 3 (different arity)
}
class ScientificCalculator extends Calculator {
@Override
double add(double a, double b) { // override (different body)
return Math.round((a + b) * 100.0) / 100.0;
}
}Q11. Can you override a static method in Java?
No. Static methods are bound at compile time based on the reference type, not the runtime object. You can hide a parent's static method by declaring one with the same signature in the subclass — that's called method hiding, not overriding. Calling Parent.staticMethod() and Child.staticMethod() invokes different methods; no polymorphism.
Q12. What is the super keyword?
References the immediate parent class. Three uses: (1) super() calls the parent constructor (must be first line in subclass constructor; auto-inserted if omitted). (2) super.method() calls an overridden parent method. (3) super.field accesses a hidden parent field.
Q13. What is the difference between this and super?
this references the current instance (current object's fields/methods). super references the parent class. this() calls another constructor in the same class (constructor chaining). super() calls the parent constructor.
Q14. Can you have a constructor in an interface?
No. Interfaces cannot be instantiated, so they don't need constructors. Abstract classes can have constructors (used when concrete subclasses call super(...)). Java 8+ interfaces can have static methods, default methods, and (Java 9+) private methods — but no constructors or instance fields.
Q15. What is an inner class?
A class declared inside another class. Four kinds: (1) member inner class — non-static, has access to outer's instance fields; (2) static nested class — doesn't need outer instance; (3) local class — declared inside a method; (4) anonymous class — one-off subclass for callbacks (largely replaced by lambdas since Java 8). Inner classes compile to separate .class files named Outer$Inner.class.
Q16. What is composition and how is it different from inheritance?
Inheritance ("is-a"): class SavingsAccount extends Account. Composition ("has-a"): class Car { Engine engine; }. Prefer composition when there's no clear "is-a" — keeps class hierarchies shallow and avoids fragile-base-class problems. The rule of thumb: ask "is X a type of Y?" — if no, use composition.
Q17. What is a final class?
A class that cannot be subclassed. Examples: java.lang.String, java.lang.Math. Useful for immutability, security, and preventing extension of utility classes. Use sparingly — marking every class final limits reuse.
Q18. What are access modifiers in Java?
| Modifier | Same class | Same package | Subclass (different package) | Other packages |
|---|---|---|---|---|
private | ✓ | — | — | — |
| default (package-private) | ✓ | ✓ | — | — |
protected | ✓ | ✓ | ✓ | — |
public | ✓ | ✓ | ✓ | ✓ |
String Handling (Q19–Q22)
Q19. Why are Java Strings immutable?
Three reasons: (1) String pooling — JVM reuses identical string literals from the constant pool, only safe if Strings can't be modified. (2) Security — strings used as keys in HashMap, URLs, file paths, database credentials; mutable strings would be a security hole. (3) Thread safety — immutable objects are inherently thread-safe. Use StringBuilder when you need to mutate (string concatenation in loops).
Q20. What is the difference between String, StringBuilder, and StringBuffer?
| Class | Mutable | Thread-safe | Use when |
|---|---|---|---|
String | No | Yes (immutable) | Default; short-lived or constant strings |
StringBuilder | Yes | No (faster) | Single-threaded string building (loop concatenation) |
StringBuffer | Yes | Yes (synchronized, slower) | Multi-threaded string building (legacy) |
// WRONG — creates 1000 intermediate String objects
String s = "";
for (int i = 0; i < 1000; i++) s += i;
// RIGHT — single mutable buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i);
String s = sb.toString();Q21. How do you compare two Strings in Java?
Use .equals() for content comparison, == only for reference identity (usually wrong for content). String.compareTo() returns negative/zero/positive for lexicographic order. String.equalsIgnoreCase() for case-insensitive content comparison.
Q22. What is the String Constant Pool?
A special area in the JVM heap where string literals are stored. When you write String s = "hello", the JVM checks the pool first — if "hello" already exists, the reference is reused; otherwise it's added. String s = new String("hello") forces a new object outside the pool (use s.intern() to add it). Pool reuse is one of the reasons Strings are immutable — otherwise modifying one would mutate all references.
Collections Framework (Q23–Q30)
Q23. What is the Collections Framework hierarchy?
| Interface | Key implementations | Order | Duplicates | Null keys |
|---|---|---|---|---|
List | ArrayList, LinkedList, Vector | Insertion order | Yes | N/A |
Set | HashSet, LinkedHashSet, TreeSet | HashSet: undefined; TreeSet: sorted | No | HashSet: 1; TreeSet: no |
Map | HashMap, LinkedHashMap, TreeMap, Hashtable | HashMap: undefined; TreeMap: sorted by key | No duplicate keys | HashMap: 1; TreeMap: no |
Queue | LinkedList, PriorityQueue, ArrayDeque | FIFO (or comparator for PriorityQueue) | Yes | Most allow 1 |
Q24. What is the difference between ArrayList and LinkedList?
ArrayList uses a dynamic array — O(1) random access by index, O(n) insertion/deletion in the middle (shifts elements). LinkedList uses a doubly-linked list — O(n) random access (must traverse), O(1) insertion/deletion at known positions. Use ArrayList as the default (90% of cases); use LinkedList for queues/deques or frequent head insertions.
Q25. What is the difference between HashMap and Hashtable?
HashMap: not synchronized (faster), allows one null key and multiple null values, introduced in Java 1.2. Hashtable: synchronized (slower, legacy), no null keys or values, legacy class from Java 1.0. Use HashMap with Collections.synchronizedMap() or ConcurrentHashMap for thread safety.
Q26. How does HashMap work internally?
HashMap stores entries in an array of buckets (default 16). When you put a key, it computes hash(key), takes modulo bucket count to get the index, and stores the entry there. Collisions (two keys hashing to the same bucket) are handled by chaining — each bucket holds a linked list of entries (converted to a red-black tree when the bucket has 8+ entries, Java 8+). Load factor (default 0.75) triggers resize when 75% full. Time: O(1) average, O(log n) worst case (tree buckets).
Q27. Why must you override both equals() and hashCode()?
HashMap (and HashSet) use hashCode() to find the bucket and equals() to find the entry within the bucket. If two equal objects have different hash codes, they'll go to different buckets and never be found. If you override equals without hashCode, HashMap breaks. The contract: equal objects must have equal hash codes; unequal objects should have different hash codes (best-effort, collisions allowed).
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee e = (Employee) o;
return id == e.id;
}
@Override
public int hashCode() {
return Objects.hash(id); // or 31 * id for primitives
}Q28. What is the difference between Comparable and Comparator?
Comparable — natural ordering: class implements compareTo, single sort sequence, modifies the class itself. Comparator — external ordering: separate class/object with compare, multiple sort sequences possible, doesn't modify the class. Use Comparable for the "natural" order (String by lexicographic, Integer by numeric); use Comparator for alternative orders (sort employees by salary, then name).
Q29. What is a fail-fast vs fail-safe iterator?
Fail-fast: throws ConcurrentModificationException if the collection is modified while iterating (ArrayList, HashMap use this — detects via a mod-count). Fail-safe: iterates over a snapshot, doesn't throw on modification (CopyOnWriteArrayList, ConcurrentHashMap). Fail-safe iterators are slower (copy overhead) but safe for concurrent modification.
Q30. What is the difference between Collection and Collections?
Collection is the root interface (List, Set, Queue extend it). Collections is a utility class with static methods like sort, shuffle, reverse, unmodifiableList, synchronizedList, min, max. Common confusion — remember: Collection = interface; Collections = utility class.
Exception Handling (Q31–Q34)
Q31. What is the difference between checked and unchecked exceptions?
Checked: subclasses of Exception (not RuntimeException); compiler forces you to handle or declare with throws (e.g., IOException, SQLException). Unchecked: subclasses of RuntimeException; compiler doesn't force handling (e.g., NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException). Errors (e.g., OutOfMemoryError): JVM-level failures, don't catch.
Q32. What is the difference between throw and throws?
throw — keyword used to actually raise an exception: throw new IllegalArgumentException("value must be positive");. throws — clause in a method signature declaring which checked exceptions the method might raise, forcing callers to handle them: public void read() throws IOException { ... }.
Q33. Can you have multiple catch blocks? Which catches first?
try {
// risky code
} catch (NumberFormatException e) {
// specific first
} catch (IllegalArgumentException e) {
// parent class — catches subclasses too if specific isn't matched
} catch (Exception e) {
// most general — last resort
}
// ORDER MATTERS: most specific first. If IllegalArgumentException comes before
// NumberFormatException, the compiler accepts it but the specific catch is unreachable.Q34. What is try-with-resources?
// Java 7+ — automatically closes anything implementing AutoCloseable
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
// process row
}
} catch (SQLException e) {
log.error("Query failed", e);
}
// conn, ps, rs all closed in reverse order, even if an exception is thrown.Multithreading (Q35–Q37)
Q35. How do you create a thread in Java?
// 1. Extend Thread (limited — can't extend anything else)
class MyThread extends Thread {
@Override public void run() { /* work */ }
}
new MyThread().start();
// 2. Implement Runnable (preferred — flexible)
class MyTask implements Runnable {
@Override public void run() { /* work */ }
}
new Thread(new MyTask()).start();
// 3. Lambda (since Java 8)
new Thread(() -> { /* work */ }).start();
// 4. ExecutorService (production code — thread pooling)
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> { /* work */ });
pool.shutdown();Q36. What is the difference between wait() and sleep()?
| Aspect | wait() | sleep() |
|---|---|---|
| Class | Object (every object has it) | Thread |
| Lock release | Releases the lock it holds | Keeps the lock |
| Wake-up | Must be called from synchronized context; wakes on notify()/notifyAll() or timeout | Wakes after timeout or interrupt() |
| Use | Inter-thread communication | Pause execution |
Q37. What is the synchronized keyword?
Marks a method or block as thread-safe — only one thread can execute the synchronized code at a time on the same monitor object. synchronized void increment() { count++; } locks this; synchronized (lock) { count++; } locks an explicit object. Modern alternative: ReentrantLock (more features — tryLock, fair queuing, condition variables).
JDBC & Coding Patterns (Q38–Q40)
Q38. What are the steps to connect to a database with JDBC?
- Load driver:
Class.forName("com.mysql.cj.jdbc.Driver");(auto-loaded since JDBC 4.0) - Get connection:
Connection c = DriverManager.getConnection(url, user, pass); - Create statement:
PreparedStatement ps = c.prepareStatement("SELECT ... WHERE id = ?"); - Bind parameters:
ps.setInt(1, id); - Execute:
ResultSet rs = ps.executeQuery(); - Process results:
while (rs.next()) { ... } - Close in reverse order (try-with-resources recommended)
Always use PreparedStatement over Statement — prevents SQL injection and is faster for repeated queries (precompiled).
Q39. Reverse a singly linked list in Java.
class Node {
int val;
Node next;
Node(int v) { this.val = v; }
}
Node reverse(Node head) {
Node prev = null, curr = head;
while (curr != null) {
Node next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Q40. Find the first non-repeated character in a String.
char firstUnique(String s) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
for (Map.Entry<Character, Integer> e : counts.entrySet()) {
if (e.getValue() == 1) return e.getKey();
}
return '\0';
}
// LinkedHashMap preserves insertion order — first entry with count 1 is the answer.4-Week Java Interview Preparation Plan
| Week | Focus | Daily Target |
|---|---|---|
| Week 1 | OOP four pillars + Java fundamentals (JDK/JRE/JVM, data types, String) | 15 MCQs + 1 coding problem (HackerRank Easy) |
| Week 2 | Collections framework (ArrayList, HashMap, HashSet internals) + exception handling | 10 MCQs + 1 collections exercise |
| Week 3 | Multithreading basics + JDBC/SQL + coding patterns (reverse linked list, two-sum, balanced parens) | 1 LeetCode Easy + 1 class design |
| Week 4 | Mock tests on HackerRank and company-specific past papers (TCS NQT, Infosys InfyTQ) | 1 full mock + 15 timed MCQs |
Resources and Next Steps
The authoritative sources listed above (Oracle Java Tutorials, Baeldung, HackerRank, LeetCode, Effective Java) are the canonical references for Java fundamentals and interview preparation. For the full 25-question curated Q&A collection at all difficulty levels (Level 1 foundational, Level 2 intermediate, Level 3 advanced), see the TutorsBot Java Interview Questions hub. For related interview prep, see our OOPs Interview Questions in Java, Python Interview Questions, and DBMS Interview Questions guides.






