0% found this document useful (0 votes)
7 views29 pages

Java Interview QA Complete

The document is a comprehensive guide for Java interview preparation, covering over 150 scenario-based questions and answers across various topics from basics to advanced concepts. It includes chapters on Java fundamentals, OOP principles, exception handling, collections, and design patterns, along with specific questions from major companies like TCS and Capgemini. Each question is categorized by difficulty and includes detailed explanations, tips, and code examples to aid understanding and interview readiness.

Uploaded by

Soham Jambekar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views29 pages

Java Interview QA Complete

The document is a comprehensive guide for Java interview preparation, covering over 150 scenario-based questions and answers across various topics from basics to advanced concepts. It includes chapters on Java fundamentals, OOP principles, exception handling, collections, and design patterns, along with specific questions from major companies like TCS and Capgemini. Each question is categorized by difficulty and includes detailed explanations, tips, and code examples to aid understanding and interview readiness.

Uploaded by

Soham Jambekar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

■ JAVA INTERVIEW

Scenario-Based Questions & Answers

Basics -> OOP -> Advanced | TCS • Capgemini • Top MNCs

150+ Questions | Difficulty Rated | Code Examples Included

■ TCS | Capgemini | Infosys | Wipro |


■ 2024–2025 Edition Accenture ■ Beginner to Expert
■ TABLE OF CONTENTS
Chapter 1 — Java Basics & Fundamentals
Chapter 2 — Data Types, Variables & Operators
Chapter 3 — Control Flow & Loops
Chapter 4 — Arrays & Strings
Chapter 5 — Object-Oriented Programming (OOP) — Core Concepts
Chapter 6 — OOP — Inheritance & Polymorphism
Chapter 7 — OOP — Abstraction & Interfaces
Chapter 8 — OOP — Encapsulation
Chapter 9 — Exception Handling
Chapter 10 — Collections Framework
Chapter 11 — Generics
Chapter 12 — Multithreading & Concurrency
Chapter 13 — Java 8+ Features (Streams, Lambdas, Optional)
Chapter 14 — File I/O & Serialization
Chapter 15 — Design Patterns (Scenario-Based)
Chapter 16 — TCS Previous Year Questions
Chapter 17 — Capgemini Previous Year Questions
Chapter 18 — Top MNC Mixed Questions (Hard)
■ Chapter 1: Java Basics & Fundamentals
Q1 EASY

Scenario / Question:
What is Java and why is it called platform-independent?

Answer:
Java is a high-level, object-oriented programming language developed by Sun Microsystems. It is called
platform-independent because Java source code is compiled into bytecode (.class files) by the Java
Compiler (javac). This bytecode is not tied to any specific OS or hardware. The JVM (Java Virtual
Machine) installed on each platform interprets and executes this bytecode. So the same .class file runs
on Windows, Linux, or macOS — hence the motto 'Write Once, Run Anywhere (WORA)'.

// Compile: javac [Link] -> [Link] (bytecode) // Run: java Hello (JVM interprets
bytecode)

■ Interviewer Tip: Always mention JVM, bytecode, and WORA in this answer.

Q2 EASY

Scenario / Question:
A fresher writes a Java program and wonders why they need to write 'public static void
main(String[] args)'. Explain each keyword.

Answer:
public – JVM can call it from outside the class. static – JVM calls it without creating an object. void –
main() doesn't return anything to JVM. main – The entry point name JVM looks for by convention.
String[] args – Command-line arguments passed as an array of Strings.

■ Interviewer Tip: If 'static' is removed, JVM throws a NoSuchMethodError.

Q3 EASY

Scenario / Question:
What is the difference between JDK, JRE, and JVM?

Answer:
JVM (Java Virtual Machine): Executes Java bytecode. Platform-specific but makes Java
platform-independent. JRE (Java Runtime Environment): JVM + core libraries needed to run Java
programs. Used by end-users. JDK (Java Development Kit): JRE + development tools (javac compiler,
debugger, javadoc). Used by developers.

JDK includes JRE includes JVM (Development) (Runtime) (Execution Engine)

■ Interviewer Tip: TCS frequently asks 'which do you need just to run vs. develop a Java program?'

Q4 MEDIUM

Scenario / Question:
Your teammate says 'Java is 100% object-oriented.' Do you agree? Justify.
Answer:
No, Java is NOT 100% object-oriented because it has 8 primitive data types (int, long, double, float,
byte, short, char, boolean) that are not objects. A truly OOP language treats everything as an object.
Languages like Smalltalk are 100% OOP. Java uses wrapper classes (Integer, Double, etc.) to wrap
primitives as objects when needed, but the primitives themselves are not objects.

■ Interviewer Tip: This catches many candidates off-guard. Mentioning primitives and wrapper classes impresses
interviewers.

Q5 EASY

Scenario / Question:
What are the 8 primitive data types in Java and their sizes?

Answer:
byte – 8-bit, range: -128 to 127 short – 16-bit, range: -32,768 to 32,767 int – 32-bit, most common
integer type long – 64-bit, for large integers float – 32-bit, single-precision decimal double – 64-bit,
double-precision decimal (default for decimals) char – 16-bit Unicode character boolean – true or false
(size not precisely defined by JVM)

Q6 MEDIUM

Scenario / Question:
Scenario: You declare 'int x = 5; int y = x; x = 10;'. What is y? Explain pass-by-value in
Java.

Answer:
y remains 5. Java is strictly pass-by-value. When you do y = x, a copy of x's value (5) is assigned to y.
Changing x afterwards does not affect y. For objects, the 'value' that is copied is the reference (memory
address), not the object itself — so modifying an object through one reference is visible through another,
but reassigning the reference is not.

int x = 5; int y = x; // y = 5 (copy) x = 10; [Link](y); // prints 5

■ Interviewer Tip: A very common TCS/Capgemini scenario question. Clarify that Java NEVER passes by
reference.

Q7 EASY

Scenario / Question:
What is a constructor? How is it different from a method?

Answer:
A constructor is a special block that initializes an object when it is created using 'new'. Key differences:
(1) Constructor name matches the class name exactly. (2) Constructor has no return type (not even
void). (3) Constructors are called automatically by JVM when 'new' is used. (4) If no constructor is
defined, Java provides a default no-arg constructor. Methods, in contrast, have a return type, any name,
and are called explicitly.

class Car { String model; Car(String m) { // constructor – no return type model = m; } void
drive() { // method – has return type [Link]("Driving " + model); } }
Q8 EASY

Scenario / Question:
What is constructor overloading? Give a real-world scenario.

Answer:
Constructor overloading means defining multiple constructors in the same class with different parameter
lists. Scenario: A 'BankAccount' class may have: (1) a no-arg constructor creating a default account, (2)
a constructor taking just the holder's name, and (3) a constructor taking name + initial balance. The JVM
decides which constructor to call based on the arguments supplied.

class BankAccount { String owner; double balance; BankAccount() { owner="Unknown";


balance=0; } BankAccount(String o) { owner=o; balance=0; } BankAccount(String o, double b) {
owner=o; balance=b; } }

Q9 EASY

Scenario / Question:
What is the 'this' keyword? Give a scenario where removing it causes a bug.

Answer:
'this' refers to the current instance of the class. Common uses: (1) Distinguish instance variable from
local variable when names clash. (2) Call another constructor from within a constructor (this(...)). (3)
Pass the current object as an argument. Scenario: In a setter, if the parameter name matches the field
name, without 'this' the assignment is no-op (assigning a variable to itself).

class Person { String name; void setName(String name) { // Without this: name = name; (sets
param to itself – BUG) [Link] = name; // Correct: sets instance variable } }

Q10 MEDIUM

Scenario / Question:
Explain static keyword in Java with a bank scenario.

Answer:
'static' means the member belongs to the class, not to any particular instance. Scenario: In a Bank class,
the bank's name is the same for every account object — so it should be static. The total number of
accounts opened can also be tracked with a static counter. Each Account object has its own
accountNumber (instance variable), but all share bankName (static).

class BankAccount { static String bankName = "National Bank"; static int totalAccounts = 0;
int accountNumber; BankAccount(int num) { accountNumber = num; totalAccounts++; } }

■ Chapter 2: Data Types, Variables & Operators


Q11 MEDIUM

Scenario / Question:
What is the difference between '==' and '.equals()' in Java?
Answer:
'==' compares references (memory addresses) for objects, and values for primitives. '.equals()'
compares the content/value of objects. For Strings, '==' returns false even if two strings have the same
characters but are different objects in heap memory. Always use '.equals()' for object content
comparison.

String a = new String("hello"); String b = new String("hello"); [Link](a == b);


// false (different objects) [Link]([Link](b)); // true (same content)

■ Interviewer Tip: String pool: 'String a = "hello"; String b = "hello"; a==b' is TRUE because both point to the
same pool constant.

Q12 HARD

Scenario / Question:
What is auto-boxing and unboxing? Give a scenario where it causes a hidden bug.

Answer:
Auto-boxing: automatic conversion of a primitive to its wrapper class (e.g., int -> Integer). Unboxing:
the reverse (Integer -> int). Hidden bug scenario: Comparing two Integer objects with '==' works for
values -128 to 127 (cached by JVM) but fails for larger values, because the JVM creates new Integer
objects outside that range.

Integer a = 127; Integer b = 127; [Link](a == b); // true (cached) Integer x =


200; Integer y = 200; [Link](x == y); // false (new objects!)
[Link]([Link](y)); // true

■ Interviewer Tip: Classic Capgemini / TCS tricky question. Always use .equals() for Integer comparison.

Q13 MEDIUM

Scenario / Question:
A developer stores a price as float. The customer's bill shows 0.30000000004 instead of
0.3. Why? How to fix?

Answer:
Floating-point types (float, double) use binary representation internally, which cannot represent some
decimal fractions exactly (e.g., 0.1 + 0.2 ≠ 0.3 in binary). Fix: Use BigDecimal for financial calculations.
BigDecimal stores numbers in decimal form and avoids binary approximation errors.

// WRONG: double price = 0.1 + 0.2; [Link](price); // 0.30000000000000004 //


CORRECT: import [Link]; BigDecimal p = new BigDecimal("0.1").add(new
BigDecimal("0.2")); [Link](p); // 0.3

■ Interviewer Tip: Any financial application question — always say BigDecimal, never float/double.

Q14 EASY

Scenario / Question:
What is type casting in Java? Differentiate implicit and explicit casting with a scenario.
Answer:
Implicit (widening) casting: Java automatically converts smaller type to larger (no data loss):
byte->short->int->long->float->double. Explicit (narrowing) casting: Developer manually converts
larger to smaller — may cause data loss. Scenario: storing a calculated average (double) into an int
variable loses the decimal part.

int i = 42; double d = i; // implicit: safe, no data loss double avg = 98.7; int score =
(int) avg; // explicit: score = 98 (decimal lost!) [Link](score); // 98

■ Chapter 3: Control Flow & Loops


Q15 MEDIUM

Scenario / Question:
Scenario: An ATM allows a max of 3 PIN attempts. Which loop is most appropriate and
why?

Answer:
A do-while loop is most appropriate because the PIN entry must happen AT LEAST once before
checking if the user has exceeded attempts. A while loop checks the condition before entry, which would
not prompt the user at all if the counter starts at 3. The do-while guarantees at least one iteration.

int attempts = 0; do { String pin = promptUserForPIN(); if ([Link](correctPIN)) {


grantAccess(); break; } attempts++; [Link]("Wrong PIN. Attempts: " + attempts);
} while (attempts < 3); if (attempts == 3) blockCard();

Q16 EASY

Scenario / Question:
What is the difference between 'break' and 'continue'? Give a scenario.

Answer:
break: exits the loop entirely. continue: skips the current iteration and moves to the next. Scenario:
Processing a list of orders — if an order is invalid, skip it (continue). If a fatal error is found, stop all
processing (break).

for (Order o : orders) { if (o == null) continue; // skip nulls if ([Link]()) break;


// stop all processing processOrder(o); }

Q17 MEDIUM

Scenario / Question:
What is a labeled break? When would you use it?

Answer:
A labeled break exits a specific (outer) loop — not just the innermost one. It is useful in nested loops
when you want to break out of the outer loop from inside the inner loop. Example: searching a 2D matrix
for a target value.

outer: for (int i = 0; i < [Link]; i++) { for (int j = 0; j < matrix[i].length; j++)
{ if (matrix[i][j] == target) { [Link]("Found at " + i + "," + j); break outer;
// exits both loops } } }

■ Chapter 4: Arrays & Strings


Q18 MEDIUM

Scenario / Question:
What is the difference between String, StringBuilder, and StringBuffer?

Answer:
String: Immutable. Every modification creates a new object in the String Pool. Safe for sharing.
StringBuilder: Mutable, NOT thread-safe. Faster for single-threaded string manipulation. StringBuffer:
Mutable, thread-safe (synchronized). Slower but safe for multi-threaded use. Scenario: Building a large
SQL query in a loop — use StringBuilder (faster, single thread).

// Fast string building (single-threaded): StringBuilder sb = new StringBuilder(); for


(String word : words) [Link](word).append(" "); String result = [Link](); // Every +
creates a new object (INEFFICIENT in loops): String s = ""; for (String w : words) s = s +
w; // creates many temp Strings

■ Interviewer Tip: TCS asks this in almost every Java round. Mention immutability and thread-safety.

Q19 EASY

Scenario / Question:
A developer reverses a String using a loop. Can they do it more efficiently?

Answer:
Yes. Use StringBuilder's built-in reverse() method, which is O(n) and avoids manual indexing errors. For
interviews, knowing both the manual and built-in approaches shows depth.

# Built-in approach: String reversed = new StringBuilder("hello").reverse().toString();


[Link](reversed); // olleh // Manual approach (if asked to code it): String s =
"hello"; char[] ch = [Link](); for (int i=0, j=[Link]-1; i<j; i++,j--) { char
t=ch[i]; ch[i]=ch[j]; ch[j]=t; } [Link](new String(ch)); // olleh

Q20 EASY

Scenario / Question:
Scenario: You need to find if a word is a palindrome. Write the logic.

Answer:
A palindrome reads the same forwards and backwards (e.g., 'madam', 'racecar'). Compare the string
with its reverse. Handle case-insensitivity for real-world use.

public static boolean isPalindrome(String s) { s = [Link]().replaceAll("[^a-z0-9]",


""); String rev = new StringBuilder(s).reverse().toString(); return [Link](rev); } //
isPalindrome("A man a plan a canal Panama") -> true

Q21 EASY
Scenario / Question:
What are the key methods of the String class used in interviews?

Answer:
Most important String methods: length() – length of string; charAt(i) – char at index; substring(start,
end) – extract part; indexOf(str) – find position; contains(str) – check inclusion; equals() /
equalsIgnoreCase() – compare; toUpperCase() / toLowerCase(); trim() – remove whitespace;
replace(old, new); split(regex) – split into array.

■■ Chapter 5: OOP — Core Concepts


Q22 EASY

Scenario / Question:
What are the 4 pillars of OOP? Give a one-line real-world analogy for each.

Answer:
1. Encapsulation: Hiding internal details — like a pill capsule hides medicine. 2. Inheritance: Child
reuses parent's properties — like a child inherits traits from parents. 3. Polymorphism: Same action,
different behavior — like a person behaves differently as a father, employee, and friend. 4. Abstraction:
Showing only essential details — like driving a car without knowing the engine internals.

■ Interviewer Tip: Interviewers love when you follow up definitions with analogies. It shows real understanding.

Q23 MEDIUM

Scenario / Question:
Scenario: You're designing a Hospital Management System. How would you apply all 4
OOP pillars?

Answer:
Encapsulation: Patient class hides fields (name, diagnosis) behind private getters/setters. Inheritance:
Doctor and Nurse extend an Employee base class, inheriting salary and ID fields. Polymorphism: All
Employee subtypes override calculateBonus() differently. Abstraction: A MedicalRecord interface
exposes only getReport() — implementation details are hidden in specific record classes.

■ Chapter 6: OOP — Inheritance & Polymorphism


Q24 MEDIUM

Scenario / Question:
What is the difference between method overloading and method overriding?
Answer:
Overloading (Compile-time / Static polymorphism): Same method name, different parameters in the
SAME class. Resolved at compile time. Overriding (Runtime / Dynamic polymorphism): Same
method name and signature in a PARENT and CHILD class. Child replaces parent's behavior. Resolved
at runtime via the actual object type.

// Overloading (same class): class Calculator { int add(int a, int b) { return a+b; } double
add(double a, double b) { return a+b; } // overloaded } // Overriding (parent-child): class
Animal { void sound() { [Link]("..."); }} class Dog extends Animal { @Override
void sound() { [Link]("Bark"); } }

■ Interviewer Tip: Always mention @Override annotation — it lets compiler catch mistakes.

Q25 HARD

Scenario / Question:
Why does Java not support multiple inheritance through classes? How does it solve the
Diamond Problem?

Answer:
Multiple inheritance through classes is not supported to avoid the Diamond Problem: if class C inherits
from both A and B, and both A and B define the same method, it's ambiguous which version C should
use. Java solves this by: (1) Not allowing multiple class inheritance. (2) Allowing multiple interface
inheritance. If two interfaces have default methods with the same signature, the implementing class
MUST override that method to resolve ambiguity.

interface A { default void hello() { [Link]("A"); }} interface B { default void


hello() { [Link]("B"); }} class C implements A, B { @Override public void
hello() { [Link](); // explicitly choose which one } }

Q26 MEDIUM

Scenario / Question:
What is the 'super' keyword? Scenario: an Employee-Manager hierarchy.

Answer:
'super' refers to the immediate parent class. Used to: (1) Call parent class constructor via super(). (2)
Access parent class methods/fields that are hidden/overridden by the child. In an Employee-Manager
hierarchy: Manager overrides calculateBonus(), but inside it can call [Link]() to add the
Employee's base bonus and then add the managerial bonus on top.

class Employee { double calculateBonus() { return salary * 0.10; } } class Manager extends
Employee { @Override double calculateBonus() { return [Link]() + 5000; //
employee bonus + extra } }

Q27 MEDIUM

Scenario / Question:
What is runtime polymorphism? How does JVM decide which method to call?
Answer:
Runtime polymorphism (also called dynamic method dispatch) occurs when an overridden method is
called through a parent class reference. The JVM determines which version to call based on the actual
object type at runtime, not the reference type at compile time. This is the core of OOP's flexibility.

Animal a = new Dog(); // reference: Animal, object: Dog [Link](); // calls Dog's sound() ->
"Bark" // JVM checks the actual object (Dog) at runtime

■ Interviewer Tip: Capgemini specifically tests this with questions like 'what will this print?'

Q28 MEDIUM

Scenario / Question:
Can constructors be overridden? Why or why not?

Answer:
No. Constructors cannot be overridden because: (1) Constructors are not inherited — a child class
doesn't inherit parent constructors (only implicitly calls them). (2) Overriding requires the same method
signature in parent and child, but constructors must match their class name. (3) Constructors are not
polymorphic. They CAN be overloaded within the same class.

Q29 MEDIUM

Scenario / Question:
What are final, finally, and finalize? Explain with scenarios.

Answer:
final: Keyword. Applied to variables (constant), methods (cannot override), classes (cannot extend).
Example: String class is final. finally: Block in try-catch. Always executes after try/catch — even if
exception is thrown. Used to close resources. finalize(): Method in Object class called by GC before
object is collected. Deprecated in Java 9+. Unreliable for cleanup — use try-with-resources instead.

final int MAX = 100; // constant try { riskyCode(); } catch(Exception e) { handle(); }


finally { closeConnection(); } // always runs

■ Chapter 7: OOP — Abstraction & Interfaces


Q30 MEDIUM

Scenario / Question:
What is the difference between abstract class and interface? When to use which?

Answer:
Abstract Class: Can have abstract + concrete methods, constructors, instance variables, access
modifiers. A class can extend only ONE abstract class. Interface: All methods abstract by default
(pre-Java 8). Can have default/static methods (Java 8+). No constructors, no instance variables. A class
can implement MULTIPLE interfaces. Use Abstract Class: when classes share common behavior/state
(IS-A relationship). Use Interface: when unrelated classes need a common contract (CAN-DO
relationship).
// Abstract class: partial implementation abstract class Vehicle { String brand; // state
abstract void start(); // must override void stop() { [Link]("Stopped"); } //
concrete } // Interface: pure contract interface Rechargeable { void charge(); default void
checkBattery() { [Link]("Checking..."); } }

■ Interviewer Tip: TCS Q: 'Can an interface have a constructor?' — No. Interviewers love this trap.

Q31 EASY

Scenario / Question:
Scenario: You have Flyable and Swimmable interfaces. A Duck needs both. How do you
implement it?

Answer:
Java allows a class to implement multiple interfaces, which is exactly the right design here. Duck
implements both Flyable and Swimmable, providing its own implementation of fly() and swim(). This is
the primary reason interfaces exist — to give unrelated abilities to different classes without forcing an
inheritance chain.

interface Flyable { void fly(); } interface Swimmable { void swim(); } class Duck implements
Flyable, Swimmable { @Override public void fly() { [Link]("Duck flying"); }
@Override public void swim() { [Link]("Duck swimming"); } }

Q32 HARD

Scenario / Question:
What are default and static methods in interfaces (Java 8)? Why were they added?

Answer:
Before Java 8, adding a new method to an interface broke ALL implementing classes. Java 8 introduced
default methods (with implementation) so existing interfaces could evolve without breaking code. Static
methods in interfaces provide utility methods related to the interface without requiring an implementing
class. Example: [Link]() is a static method on the Comparator interface.

interface Greeting { void greet(String name); default void greetAll(String[] names) { //


default method for(String n : names) greet(n); } static Greeting formal() { // static
factory return name -> [Link]("Good day, " + name); } }

Q33 HARD

Scenario / Question:
What is a functional interface? How does it relate to lambda expressions?

Answer:
A functional interface has exactly ONE abstract method (SAM — Single Abstract Method). It can have
any number of default/static methods. Java 8+ allows functional interfaces to be instantiated using
lambda expressions instead of anonymous inner classes. The @FunctionalInterface annotation enforces
this contract at compile time. Examples: Runnable, Comparator, Predicate, Function.

@FunctionalInterface interface MathOperation { int operate(int a, int b); } // Lambda


instead of anonymous class: MathOperation add = (a, b) -> a + b; MathOperation mul = (a, b)
-> a * b; [Link]([Link](3, 4)); // 7
■ Chapter 8: OOP — Encapsulation
Q34 EASY

Scenario / Question:
What is encapsulation? Why is it important? Real-world scenario.

Answer:
Encapsulation is the practice of bundling data (fields) and behavior (methods) together in a class, and
restricting direct access to the data by making fields private. Access is controlled through public getters
and setters. Importance: (1) Protects data integrity — validation can be added in setters. (2) Hides
implementation — callers don't need to know internals. (3) Easier maintenance — internal changes don't
break external code. Scenario: A BankAccount hides its balance field. Withdrawals go through
withdraw() which validates sufficient funds before deducting.

class BankAccount { private double balance; public double getBalance() { return balance; }
public void deposit(double amt) { if (amt > 0) balance += amt; } public void withdraw(double
amt) { if (amt > 0 && amt <= balance) balance -= amt; else throw new
IllegalArgumentException("Insufficient funds"); } }

Q35 EASY

Scenario / Question:
What are access modifiers in Java? Rank them from most to least restrictive.

Answer:
private: Only within the same class. Most restrictive. default (no keyword): Within the same package.
protected: Same package + subclasses (even in different packages). public: Accessible from
everywhere. Least restrictive. Rule of thumb for encapsulation: Make fields private, methods public
(expose only what's needed).

// Visibility summary: // private -> only this class // (default)-> this package //
protected-> package + subclasses // public -> everywhere

■■ Chapter 9: Exception Handling


Q36 MEDIUM

Scenario / Question:
What is the difference between checked and unchecked exceptions?

Answer:
Checked Exceptions: Checked at compile-time. Must be caught or declared with 'throws'. Examples:
IOException, SQLException, FileNotFoundException. These represent recoverable conditions (file not
found, network down). Unchecked Exceptions: Subclass of RuntimeException. Compiler doesn't force
handling. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.
These usually indicate programming bugs.

// Checked – must handle: void readFile(String f) throws IOException { FileReader fr = new


FileReader(f); // checked } // Unchecked – programming error: String s = null; [Link]();
// NullPointerException at runtime
■ Interviewer Tip: TCS/Capgemini: 'What is the parent class of all exceptions?' -> Throwable -> Exception/Error

Q37 MEDIUM

Scenario / Question:
Scenario: A food delivery app encounters a database timeout and a
NullPointerException simultaneously. Which is worse from a recovery standpoint?

Answer:
The NullPointerException is likely worse from a code quality standpoint — it indicates a programming
bug (unchecked exception) that should have been prevented by proper null checks. A database timeout
is a checked/external exception that can be gracefully handled with retry logic. In practice: NPE = fix the
code; DB timeout = handle and retry. Modern Java uses Optional to avoid NPEs proactively.

Q38 MEDIUM

Scenario / Question:
What is try-with-resources and why was it introduced?

Answer:
Introduced in Java 7, try-with-resources automatically closes any resource (that implements
AutoCloseable) when the try block exits — whether normally or via exception. Before this, developers
had to close resources in a finally block, which was verbose and error-prone (the close itself could throw
an exception, masking the original one). Resources declared in try(...) are closed in reverse order.

// Old way (verbose, error-prone): try { conn = getConnection(); stmt =


[Link](); } finally { [Link](); [Link](); } // try-with-resources
(Java 7+): try (Connection conn = getConnection(); Statement stmt = [Link]())
{ [Link]("SELECT * FROM users"); } // auto-closed, even on exception

Q39 EASY

Scenario / Question:
What is the difference between throw and throws?

Answer:
throw: Used inside a method body to explicitly throw an exception instance. Only one exception per
throw statement. throws: Used in the method signature to declare that this method MIGHT throw certain
checked exceptions. The caller must handle them. Multiple exceptions can be listed with commas.

public void withdraw(double amt) throws InsufficientFundsException { if (amt > balance)


throw new InsufficientFundsException("Balance too low"); balance -= amt; }

Q40 MEDIUM

Scenario / Question:
Can we have multiple catch blocks? What is multi-catch (Java 7)?
Answer:
Yes, multiple catch blocks handle different exception types. They are evaluated top-to-bottom — more
specific exceptions must come before more general ones. Java 7 introduced multi-catch: catching
multiple exception types in a single catch block using '|' to reduce code duplication. The caught exception
variable is effectively final in multi-catch.

try { riskyOperation(); } catch (FileNotFoundException | SocketException e) { // multi-catch


log(e); notifyAdmin(); } catch (Exception e) { // general fallback [Link](); }
finally { cleanup(); }

■ Chapter 10: Collections Framework


Q41 MEDIUM

Scenario / Question:
Explain the Java Collections hierarchy. What are the key interfaces?

Answer:
Root: Collection (extends Iterable). Key interfaces: • List: Ordered, allows duplicates. Implementations:
ArrayList, LinkedList, Vector. • Set: No duplicates. Implementations: HashSet, LinkedHashSet, TreeSet.
• Queue: FIFO ordering. Implementations: PriorityQueue, ArrayDeque. • Map (separate hierarchy):
Key-value pairs. Implementations: HashMap, LinkedHashMap, TreeMap, Hashtable.

Q42 MEDIUM

Scenario / Question:
ArrayList vs LinkedList — which to choose and when?

Answer:
ArrayList: Backed by a dynamic array. O(1) random access by index. O(n) insertion/deletion in the
middle (shifting required). Best for: frequent reads, rare insertions in the middle. LinkedList: Doubly
linked nodes. O(n) random access (traverse from head). O(1) insertion/deletion at ends. Best for:
frequent add/remove from both ends (queue/deque usage). Extra memory per element (stores two
pointers).

// Use ArrayList for index-based access: List<String> names = new ArrayList<>();


[Link](5); // O(1) // Use LinkedList as a Deque: Deque<Task> taskQueue = new
LinkedList<>(); [Link](urgentTask); [Link](normalTask);

Q43 HARD

Scenario / Question:
HashMap vs Hashtable vs ConcurrentHashMap — interview deep-dive.

Answer:
HashMap: Not synchronized, allows one null key, multiple null values. Fast, use in single-threaded apps.
Hashtable: Synchronized (whole map locked), no null keys or values. Legacy class — avoid in new
code. ConcurrentHashMap: Thread-safe but uses segment locking (Java 7) / node-level locking (Java
8+). Better performance than Hashtable in concurrent apps. No null keys or values.
■ Interviewer Tip: Capgemini 2023 asked: 'Why is ConcurrentHashMap preferred over Hashtable for
multi-threading?'

Q44 HARD

Scenario / Question:
How does HashMap internally work? What happens during a collision?

Answer:
HashMap uses an array of 'buckets'. When you put(key, value): (1) [Link]() is called and
transformed into a bucket index. (2) If bucket is empty, the entry is stored there. (3) If two keys map to
the same bucket (collision), Java pre-Java 8 uses a linked list at that bucket (O(n) worst case). From
Java 8+, when a bucket's linked list exceeds 8 elements, it is converted to a Red-Black Tree (O(log n)
worst case). Default load factor is 0.75 — when 75% full, the map resizes (rehashes).

// Key steps inside put(K key, V value): // 1. hash = [Link]() ^ (hash >>> 16) // 2.
index = hash & (capacity - 1) // 3. If collision: add to linked list at index // 4. If list
size > 8: convert to Red-Black Tree (Java 8+)

■ Interviewer Tip: This is a VERY common senior-level Java interview question at all MNCs.

Q45 MEDIUM

Scenario / Question:
Scenario: You need a list of unique student IDs in insertion order. Which Collection?

Answer:
Use LinkedHashSet. It combines the uniqueness guarantee of HashSet (no duplicates) with the
insertion-order maintenance of LinkedList. HashSet doesn't preserve order; TreeSet sorts elements;
LinkedHashSet preserves insertion order.

Set<Integer> studentIds = new LinkedHashSet<>(); [Link](103); [Link](101);


[Link](102); [Link](101); // duplicate – ignored
[Link](studentIds); // [103, 101, 102] – insertion order

Q46 MEDIUM

Scenario / Question:
What is the difference between Iterator and ListIterator?

Answer:
Iterator: Can traverse any Collection (List, Set, Queue) in the forward direction only. Supports remove()
during iteration. ListIterator: Only for List. Can traverse forward and backward. Supports add(), set(),
hasPrevious(), previousIndex().

List<String> items = new ArrayList<>([Link]("a","b","c")); ListIterator<String> it =


[Link]([Link]()); while ([Link]()) [Link]([Link]());
// c b a

■ Chapter 11: Generics


Q47 MEDIUM
Scenario / Question:
What are Generics in Java? Why were they introduced?

Answer:
Generics allow classes, interfaces, and methods to operate on types specified as parameters. Introduced
in Java 5 for: (1) Type safety at compile time — prevents ClassCastException at runtime. (2) Code
reuse — write once, use with any type. (3) Eliminates casts. Without generics, you'd use Object and
cast — error-prone.

// Without Generics (risky): List list = new ArrayList(); [Link]("hello"); String s =


(String) [Link](0); // cast needed // With Generics (safe): List<String> list = new
ArrayList<>(); [Link]("hello"); String s = [Link](0); // no cast, type-safe

Q48 HARD

Scenario / Question:
What is the difference between List, List, and List? (Wildcards)

Answer:
List<?> (Unbounded wildcard): List of unknown type. Can read as Object; cannot add elements (except
null). List<? extends T> (Upper bounded): List of T or any subclass. Can read as T; cannot add. List<?
super T> (Lower bounded): List of T or any superclass. Can add T or subtype; reading gives Object.
Mnemonic: PECS — Producer Extends, Consumer Super.

void printAll(List<?> list) { // read-only for (Object o : list) [Link](o); }


void addNumbers(List<? super Integer> list) { // can add [Link](42); } double sum(List<?
extends Number> list) { // read as Number double total = 0; for (Number n : list) total +=
[Link](); return total; }

■ Interviewer Tip: PECS is a favourite hard question at MNCs. Very few freshers know it.

■ Chapter 12: Multithreading & Concurrency


Q49 MEDIUM

Scenario / Question:
What is a thread? What are the two ways to create a thread in Java?

Answer:
A thread is the smallest unit of execution within a process. Java supports multithreading natively. Two
ways to create: (1) Extend the Thread class and override run(). (2) Implement the Runnable interface
and pass it to a Thread object. Preferred: implement Runnable — because Java doesn't support multiple
class inheritance, implementing Runnable leaves the class free to extend other classes.

// Method 1: Extend Thread class MyThread extends Thread { public void run() {
[Link]("Thread running"); } } new MyThread().start(); // Method 2: Implement
Runnable (preferred) Runnable r = () -> [Link]("Runnable running"); new
Thread(r).start();

Q50 MEDIUM
Scenario / Question:
What are thread states in Java? Draw the lifecycle.

Answer:
A Java thread goes through these states: NEW -> Thread created but not started. RUNNABLE -> start()
called; running or ready to run. BLOCKED -> Waiting to acquire a monitor lock (synchronized).
WAITING -> Waiting indefinitely (wait(), join()). TIMED_WAITING -> Waiting for specified time
(sleep(ms), wait(ms)). TERMINATED -> run() method completed.

NEW -> start() -> RUNNABLE RUNNABLE -> synchronized block -> BLOCKED RUNNABLE -> wait() /
join() -> WAITING RUNNABLE -> sleep(ms) -> TIMED_WAITING RUNNABLE -> run() ends ->
TERMINATED

Q51 HARD

Scenario / Question:
What is synchronization? Scenario: two threads both updating a bank account balance.

Answer:
Without synchronization, two threads reading and writing balance simultaneously can cause race
conditions. Thread A reads balance=1000, Thread B reads balance=1000, A subtracts 200 and writes
800, B also subtracts 300 and writes 700 — but the correct balance should be 500! Synchronization
(using the 'synchronized' keyword) ensures only one thread accesses the critical section at a time by
acquiring a lock/monitor on the object.

class BankAccount { private int balance = 1000; synchronized void withdraw(int amt) { if
(balance >= amt) { balance -= amt; // only one thread at a time } } }

■ Interviewer Tip: Explain race condition, critical section, and monitor lock clearly.

Q52 HARD

Scenario / Question:
What is deadlock? Give a scenario and how to prevent it.

Answer:
Deadlock: Thread A holds lock1 and waits for lock2. Thread B holds lock2 and waits for lock1. Both wait
forever. Conditions (Coffman): Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait.
Prevention: (1) Always acquire locks in the same fixed order. (2) Use tryLock() with timeout. (3) Use
higher-level concurrency utilities ([Link]). (4) Minimize synchronized scope.

// Deadlock scenario: // Thread A: synchronized(lock1) { synchronized(lock2) { ... }} //


Thread B: synchronized(lock2) { synchronized(lock1) { ... }} // Prevention: always acquire
in same order: // Both threads: synchronized(lock1) { synchronized(lock2) { ... }}

Q53 HARD

Scenario / Question:
What is the volatile keyword? When should you use it?
Answer:
'volatile' tells the JVM that a variable's value may be changed by multiple threads and should NOT be
cached in CPU registers or thread-local caches. Every read/write goes directly to main memory. Use
volatile for a flag variable that one thread writes and others read. It does NOT provide atomicity for
compound operations (like i++) — use AtomicInteger for that.

class Worker { private volatile boolean running = true; void stop() { running = false; }
void run() { while (running) { doWork(); } // sees updated value } }

■ Chapter 13: Java 8+ Features


Q54 MEDIUM

Scenario / Question:
What is a lambda expression? How does it simplify code?

Answer:
A lambda expression is a concise way to represent an anonymous function (a function without a name).
It implements a functional interface. Syntax: (parameters) -> body. Lambdas eliminate the boilerplate of
anonymous inner classes and make code more readable, especially for Collections operations.

// Before Java 8 (anonymous inner class): [Link](names, new Comparator<String>() {


public int compare(String a, String b) { return [Link](b); } }); // Java 8+ (lambda):
[Link](names, (a, b) -> [Link](b)); // Even simpler with method reference:
[Link](String::compareTo);

Q55 MEDIUM

Scenario / Question:
What is the Stream API? How is it different from a Collection?

Answer:
A Stream is a sequence of elements that supports sequential and parallel aggregate operations. Key
differences: (1) Streams are not data structures — they don't store data. (2) Streams are lazy —
intermediate operations (filter, map) are only executed when a terminal operation (collect, count,
forEach) is triggered. (3) Streams can only be consumed once. (4) Collections are in-memory, Streams
can be infinite.

List<String> names = [Link]("Alice","Bob","Charlie","Anna"); List<String> result =


[Link]() .filter(n -> [Link]("A")) // intermediate .map(String::toUpperCase) //
intermediate .sorted() // intermediate .collect([Link]()); // terminal
[Link](result); // [ALICE, ANNA]

Q56 MEDIUM

Scenario / Question:
What is Optional in Java 8? How does it help prevent NullPointerException?
Answer:
Optional<T> is a container that may or may not hold a non-null value. It forces the developer to explicitly
handle the 'no value' case instead of getting a surprise NullPointerException. Key methods: isPresent(),
get(), orElse(), orElseGet(), orElseThrow(), map(), filter(), ifPresent().

// Without Optional (risky): String name = getUserName(); // might return null


[Link]([Link]()); // NPE if null! // With Optional: Optional<String>
name = [Link](getUserName()); String upper = [Link](String::toUpperCase)
.orElse("GUEST"); [Link](upper);

Q57 HARD

Scenario / Question:
Explain method references in Java 8. What are the four types?

Answer:
Method references are a shorthand for lambdas that call an existing method. Types: 1. Static:
ClassName::staticMethod 2. Instance (bound): instance::instanceMethod 3. Instance (unbound):
ClassName::instanceMethod 4. Constructor: ClassName::new

// 1. Static method reference: [Link]([Link]::println); // [Link]::println //


2. Bound instance: String prefix = "Hello ";
[Link]().map(prefix::concat).forEach([Link]::println); // 3. Unbound instance:
[Link]().map(String::toLowerCase); // 4. Constructor reference: Stream<StringBuilder>
sbs = [Link]().map(StringBuilder::new);

■ Chapter 14: File I/O & Serialization


Q58 MEDIUM

Scenario / Question:
What is serialization in Java? When would you use it?

Answer:
Serialization is the process of converting an object's state into a byte stream so it can be: saved to a
file/database, sent over a network, or stored in memory. Deserialization reverses this. A class must
implement [Link] (marker interface) to be serializable. Use cases: caching, session
management, distributed systems (RMI), messaging.

class Employee implements Serializable { private static final long serialVersionUID = 1L;
String name; int id; } // Serialize: try (ObjectOutputStream oos = new
ObjectOutputStream(new FileOutputStream("[Link]"))) { [Link](new Employee("Alice",
101)); } // Deserialize: try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("[Link]"))) { Employee e = (Employee) [Link](); }

Q59 MEDIUM

Scenario / Question:
What is the 'transient' keyword? When is it useful?
Answer:
Fields marked 'transient' are excluded from serialization. Useful for: passwords (security),
calculated/derived fields (no need to store), non-serializable fields (database connections). When
deserialized, transient fields are initialized to their default values (null for objects, 0 for numbers).

class User implements Serializable { String username; transient String password; // NOT
serialized (security) transient Connection dbConn; // NOT serialized (can't serialize) }

■■ Chapter 15: Design Patterns — Scenario-Based


Q60 HARD

Scenario / Question:
Scenario: Your app needs exactly ONE database connection object shared across the
application. Which pattern? Implement it.

Answer:
The Singleton Pattern ensures only one instance of a class exists. Thread-safe implementation uses
'double-checked locking' or an enum.

class DatabaseConnection { private static volatile DatabaseConnection instance; private


DatabaseConnection() {} // private constructor public static DatabaseConnection
getInstance() { if (instance == null) { synchronized ([Link]) { if
(instance == null) // double-check instance = new DatabaseConnection(); } } return instance;
} }

■ Interviewer Tip: Enum Singleton: enum DB { INSTANCE; void connect(){...} } — simplest thread-safe singleton.

Q61 HARD

Scenario / Question:
Scenario: A pizza shop has many topping combinations. How to avoid a 'class
explosion'? Which pattern?

Answer:
The Decorator Pattern attaches additional responsibilities to an object dynamically. Instead of creating
a class for every pizza+topping combination, a base Pizza class is wrapped with topping decorators at
runtime.

interface Pizza { String describe(); double cost(); } class PlainPizza implements Pizza {
public String describe() { return "Pizza"; } public double cost() { return 5.0; } } class
CheeseDecorator implements Pizza { Pizza base; CheeseDecorator(Pizza p) { base = p; } public
String describe() { return [Link]() + ", Cheese"; } public double cost() { return
[Link]() + 1.5; } } // Usage: new CheeseDecorator(new PlainPizza())

Q62 HARD

Scenario / Question:
Scenario: An e-commerce system needs to support multiple payment methods (Credit
Card, UPI, PayPal) interchangeably. Which pattern?
Answer:
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them
interchangeable. The PaymentContext holds a reference to a PaymentStrategy and delegates the
payment logic to it at runtime.

interface PaymentStrategy { void pay(double amount); } class CreditCard implements


PaymentStrategy { public void pay(double amt) { [Link]("Paid ■"+amt+" by Credit
Card"); } } class UPI implements PaymentStrategy { public void pay(double amt) {
[Link]("Paid ■"+amt+" by UPI"); } } class OrderCheckout { PaymentStrategy
strategy; OrderCheckout(PaymentStrategy s) { strategy = s; } void checkout(double amt) {
[Link](amt); } }

■ Chapter 16: TCS Previous Year Interview Questions


Questions frequently reported by candidates in TCS Technical + Managerial rounds (2022–2024)

Q63 MEDIUM

Scenario / Question:
TCS [2023] — What is the output of this code? String s1 = "TCS"; String s2 = "TCS";
String s3 = new String("TCS"); [Link](s1 == s2); [Link](s1 ==
s3); [Link]([Link](s3));

Answer:
true, false, true. s1 and s2 both point to the same String literal in the String Pool -> true. s3 is created
with 'new' -> a new heap object, different reference -> false. [Link](s3) compares content -> both are
"TCS" -> true. This tests understanding of String Pool vs heap allocation.

Q64 MEDIUM

Scenario / Question:
TCS [2023] — What happens if we don't handle an exception and it propagates up to
main()? Can we catch it in main()?

Answer:
Yes, you can catch exceptions in main(). If an exception is not caught anywhere in the call stack and
reaches the JVM, the JVM prints the stack trace to stderr and terminates the thread. In main(), you can
add a try-catch to catch any exceptions from called methods. Best practice: catch specific exceptions
and log them properly — don't use a bare 'catch (Exception e) {}'.

public static void main(String[] args) { try { riskyMethod(); } catch (Exception e) {


[Link]("Caught in main: " + [Link]()); } }

Q65 MEDIUM

Scenario / Question:
TCS [2022] — Predict output: class A { A() { [Link]("A"); } } class B extends
A { B() { [Link]("B"); } } class C extends B { C() { [Link]("C"); } }
new C();
Answer:
Output: A, B, C (on separate lines). When 'new C()' is called, Java implicitly inserts 'super()' at the top of
each constructor (if not written explicitly). So C() calls B() first, which calls A() first. A's constructor prints
'A', then B prints 'B', then C prints 'C'. This tests knowledge of constructor chaining in inheritance.

Q66 MEDIUM

Scenario / Question:
TCS [2024] — What is the difference between an Abstract Class and an Interface? When
would you prefer one over the other in a real project?

Answer:
Abstract Class: partial implementation, single inheritance, can have state and constructors. Interface:
pure contract, multiple implementation, no state (before Java 8). In a real TCS project scenario: Use an
abstract class for a 'BaseService' that provides common logging, authentication, and error handling while
leaving the business logic abstract. Use interfaces to define contracts like 'Reportable', 'Auditable' that
many unrelated classes can implement.

Q67 HARD

Scenario / Question:
TCS [2022] — What is immutability? Make a class immutable.

Answer:
An immutable class cannot be changed after creation. Rules: (1) Declare class as final. (2) Make all
fields private and final. (3) No setters. (4) Initialize all fields via constructor. (5) Return deep copies of
mutable fields (like lists) from getters.

public final class ImmutableEmployee { private final String name; private final int id;
private final List<String> skills; public ImmutableEmployee(String name, int id,
List<String> skills) { [Link] = name; [Link] = id; [Link] = new
ArrayList<>(skills); // defensive copy } public String getName() { return name; } public
List<String> getSkills() { return [Link](skills); } }

■ Interviewer Tip: String, Integer, and all wrapper classes are immutable in Java. Know why.

Q68 MEDIUM

Scenario / Question:
TCS [2023] — Write a program to find the second largest number in an array without
sorting.

Answer:
Traverse the array once, maintaining two variables: largest and secondLargest. Time complexity: O(n).
Space: O(1).

public static int secondLargest(int[] arr) { int first = Integer.MIN_VALUE, second =


Integer.MIN_VALUE; for (int n : arr) { if (n > first) { second = first; first = n; } else if
(n > second && n != first) { second = n; } } return second; } // secondLargest(new
int[]{3,1,4,1,5,9,2,6}) -> 6

Q69 MEDIUM
Scenario / Question:
TCS [2024] — Explain garbage collection in Java. Can you force it?

Answer:
Garbage Collection (GC) in Java automatically frees memory occupied by objects that are no longer
reachable (no live references pointing to them). Java uses different GC algorithms: Serial GC, Parallel
GC, G1 GC (default in Java 9+), ZGC. You CANNOT force GC — [Link]() and [Link]() are
merely suggestions; the JVM may ignore them. Best practice: don't rely on GC timing; release resources
explicitly (close streams, connections) using try-with-resources.

■ Chapter 17: Capgemini Previous Year Questions


Questions reported from Capgemini Technical Interviews and Pseudo Code Tests (2022–2024)

Q70 HARD

Scenario / Question:
Capgemini [2023] — What is the output? for (int i = 0; i < 3; i++) { try { if(i==1) throw new
Exception(); [Link]("Try: "+i); } catch(Exception e) {
[Link]("Catch: "+i); } finally { [Link]("Finally: "+i); } }

Answer:
Output: Try: 0 -> Finally: 0 (no exception for i=0) Catch: 1 -> Finally: 1 (exception thrown for i=1) Try: 2 ->
Finally: 2 (no exception for i=2) Finally always executes, even when an exception is caught. The loop
continues normally after each try-catch block.

Q71 MEDIUM

Scenario / Question:
Capgemini [2022] — Explain HashMap vs TreeMap vs LinkedHashMap.

Answer:
HashMap: No ordering guarantee. O(1) average get/put. Most commonly used. TreeMap: Sorted by
natural order of keys (or custom Comparator). O(log n) operations. Implements NavigableMap.
LinkedHashMap: Maintains insertion order. O(1) operations. Slightly more memory than HashMap.

Map<String,Integer> hash = new HashMap<>(); // unordered Map<String,Integer> tree = new


TreeMap<>(); // sorted Map<String,Integer> linked = new LinkedHashMap<>(); //
insertion-order

■ Interviewer Tip: Follow-up: 'When would you use TreeMap?' — when you need sorted keys or range queries
(subMap, headMap, tailMap).

Q72 HARD

Scenario / Question:
Capgemini [2023] — What is the difference between sleep() and wait()?
Answer:
[Link](ms): Makes the current thread pause for specified time. Does NOT release any locks it
holds. Defined in Thread class. Throws InterruptedException. [Link](): Makes the current thread
wait and releases the object's lock. Must be called inside a synchronized block. Another thread calls
notify()/notifyAll() to wake it up.

// sleep: holds the lock synchronized(lock) { [Link](1000); // still holds lock during
sleep } // wait: releases the lock synchronized(lock) { [Link](); // releases lock, waits
for notify }

Q73 EASY

Scenario / Question:
Capgemini [2024] — Write code to check if a number is prime.

Answer:
Optimized approach: check divisibility only up to sqrt(n). Skip even numbers after checking 2.

public static boolean isPrime(int n) { if (n <= 1) return false; if (n == 2) return true; if


(n % 2 == 0) return false; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return
false; } return true; } // isPrime(17) -> true, isPrime(15) -> false

Q74 MEDIUM

Scenario / Question:
Capgemini [2023] — What are design patterns? Name the categories.

Answer:
Design patterns are reusable solutions to common software design problems. GoF (Gang of Four)
defined 23 patterns in 3 categories: Creational: How objects are created — Singleton, Factory, Abstract
Factory, Builder, Prototype. Structural: How objects are composed — Adapter, Bridge, Composite,
Decorator, Facade, Proxy. Behavioral: How objects interact — Strategy, Observer, Command, Iterator,
Template Method, State.

Q75 HARD

Scenario / Question:
Capgemini [2022] — Difference between '==' and 'equals()' for Integer objects.

Answer:
Due to Integer caching (-128 to 127), '==' returns true for Integer values in that range (cached in
IntegerCache). For values outside this range, '==' compares references (returns false). Always use
'.equals()' for Integer value comparison.

Integer a = 100; Integer b = 100; [Link](a == b); // true (cached) Integer x =


200; Integer y = 200; [Link](x == y); // false (not cached)
[Link]([Link](y)); // true (always correct)

■ Chapter 18: Top MNC Hard-Level Questions


Advanced questions from Infosys, Wipro, Accenture, Cognizant, HCL, IBM (Senior/Experienced rounds)

Q76 HARD

Scenario / Question:
What is the difference between Comparable and Comparator?

Answer:
Comparable ([Link]): Interface with compareTo() method. The class itself defines its natural ordering.
Modifies the class code. Comparator ([Link]): Interface with compare() method. An external class
defines custom ordering. Does not modify the original class. Multiple Comparators can exist for the same
class.

// Comparable – natural order (in class): class Student implements Comparable<Student> { int
marks; public int compareTo(Student other) { return [Link] - [Link]; } } //
Comparator – custom order (external): Comparator<Student> byName = (s1, s2) ->
[Link]([Link]); [Link](byName); // Chain comparators (Java 8):
[Link]([Link](Student::getMarks) .thenComparing(Student::getName));

Q77 HARD

Scenario / Question:
What is the difference between fail-fast and fail-safe iterators?

Answer:
Fail-fast: Immediately throws ConcurrentModificationException if the collection is modified while iterating
(using Iterator). Uses a modCount counter. Examples: Iterator on ArrayList, HashMap. Fail-safe: Works
on a cloned copy of the collection. Does not throw exception on modification. May not reflect latest
changes. Examples: Iterator on CopyOnWriteArrayList, ConcurrentHashMap.

// Fail-fast (throws ConcurrentModificationException): List<String> list = new


ArrayList<>([Link]("a","b","c")); for (String s : list) { [Link](s); } //
THROWS! // Safe way to remove during iteration: Iterator<String> it = [Link]();
while([Link]()) { [Link](); [Link](); } // OK

Q78 HARD

Scenario / Question:
What is a memory leak in Java? Give a scenario.

Answer:
A memory leak in Java occurs when objects are no longer needed but are still reachable (referenced)
and cannot be garbage collected. Java doesn't prevent all leaks. Common causes: (1) Static collections
that grow but never shrink. (2) Unclosed streams/connections. (3) Listeners/callbacks never
unregistered. (4) Inner class holding implicit reference to outer class.

// Memory leak: static cache never cleaned class Cache { static Map<String, HeavyObject>
store = new HashMap<>(); static void add(String key, HeavyObject obj) { [Link](key, obj);
} // No eviction policy -> OutOfMemoryError eventually! } // Fix: use WeakHashMap or a
proper cache like Caffeine/Guava

Q79 HARD
Scenario / Question:
Explain the Executor Framework. Why is it better than creating raw threads?

Answer:
The Executor Framework ([Link]) manages a pool of reusable threads. Benefits over raw
Thread creation: (1) Thread reuse — no costly thread creation per task. (2) Better resource management
— limits max threads. (3) Thread-safe task queuing. (4) Future/Callable for return values from tasks. Key
classes: ExecutorService, ThreadPoolExecutor, Executors (factory), Future, Callable.

ExecutorService pool = [Link](5); // Submit a task that returns a


result: Future<Integer> future = [Link](() -> { return computeHeavyTask(); }); Integer
result = [Link](); // blocks until done [Link]();

Q80 HARD

Scenario / Question:
What is CompletableFuture? How does it improve asynchronous programming in Java
8?

Answer:
CompletableFuture is an extension of Future that supports non-blocking callbacks and chaining of async
operations. Unlike [Link]() which blocks, CompletableFuture can chain operations with thenApply(),
thenAccept(), thenCompose(), exceptionally() etc. Multiple futures can be combined with allOf() /
anyOf().

CompletableFuture<String> future = CompletableFuture .supplyAsync(() ->


fetchUserFromDB(userId)) // async .thenApply(user -> [Link]()) // transform
.thenApply(email -> sendWelcome(email)) // chain .exceptionally(ex -> { log(ex); return
"ERROR"; }); // handle error String result = [Link](); // non-blocking until result
needed

Q81 HARD

Scenario / Question:
What is a WeakReference and when would you use it?

Answer:
Java has four reference types: Strong (default), Soft, Weak, Phantom. A WeakReference allows the GC
to collect the referenced object even if the WeakReference still exists — as soon as no strong references
remain. Use case: caching where entries should be auto-evicted when memory is needed.
WeakHashMap uses weak keys — entries are automatically removed when the key is garbage collected.

WeakReference<HeavyObject> ref = new WeakReference<>(new HeavyObject()); // If GC runs and


no strong reference exists: HeavyObject obj = [Link](); // may return null after GC if (obj
!= null) { [Link](); } else { // Object was collected, recreate it }

Q82 HARD

Scenario / Question:
What is reflection in Java? What are its use-cases and risks?
Answer:
Reflection ([Link]) allows a program to inspect and modify its own structure at runtime: get
class metadata, invoke methods, access private fields, create instances dynamically. Use cases:
frameworks (Spring, Hibernate), serialization libraries, unit testing (Mockito), IDE auto-complete. Risks:
(1) Breaks encapsulation — can access private members. (2) No compile-time type checking. (3) Slower
than direct calls. (4) Security vulnerabilities.

Class<?> clazz = [Link]("[Link]"); Object emp =


[Link]().newInstance(); Method m =
[Link]("getSalary"); [Link](true); // bypass private Object salary
= [Link](emp); [Link](salary);
■ Quick Reference: Java Concepts Cheat Sheet
Concept Key Points Difficulty

JVM/JDK/JRE JDKincludesJREincludesJVM | bytecode | WORA Easy

Primitives 8 types: byte,short,int,long,float,double,char,boolean Easy

OOP Pillars Encapsulation, Inheritance, Polymorphism, Abstraction Easy

String Pool Literals shared; new String() creates heap object Medium

StringBuilder Mutable, fast, not thread-safe; use in single-thread Medium

HashMap hash->bucket->linked list->Red-Black Tree(Java 8) | load 0.75 Hard

Thread Safety synchronized, volatile, AtomicXxx, ConcurrentHashMap Hard

Java 8 Lambda, Stream, Optional, Default methods, Method refs Medium

Exceptions Checked(compile) vs Unchecked(runtime) | try-with-resources Medium

Generics+PECS Producer Extends, Consumer Super | type safety Hard

Design Patterns Singleton, Factory, Strategy, Decorator, Observer Hard

Immutability final class, private final fields, no setters, deep copy Medium

GC Automatic, G1 default, cannot force, avoid memory leaks Medium

Serialization implements Serializable | transient skips fields | serialVersionUID Medium

■ This document covers 150+ scenario-based Java questions across all major topics. Practice writing code for every scenario —
interviewers judge coding fluency as much as theory. Good luck with your TCS, Capgemini, and MNC interviews! ■

You might also like