☕ Java Interview Notes | Beginner to Advanced | Placement Ready
☕ JAVA INTERVIEW NOTES
Beginner → Intermediate → Advanced | Placement Drive Ready
Simple Language • Code Examples • Interview Tips • Real Questions
SECTION 1: Java Basics (Beginner Level)
1.1 What is Java?
Q1. What is Java? Why is it platform-independent?
A: Java is a programming language created by Sun Microsystems in 1995. It is platform-independent
because of a concept called Write Once Run Anywhere (WORA). When you write Java code, it compiles
into bytecode (not machine code). This bytecode runs on any machine that has a JVM (Java Virtual
Machine) installed. So the same .class file works on Windows, Mac, and Linux without recompiling.
📌 Note: Java code → Compiler → Bytecode (.class file) → JVM reads it → Runs on any OS
Q2. What is the difference between JDK, JRE, and JVM?
A: JVM (Java Virtual Machine): The engine that actually runs your Java bytecode. It converts bytecode
into machine-specific instructions.
A: JRE (Java Runtime Environment): JVM + all the libraries your Java program needs to run. If you just
want to RUN a Java program, install JRE.
A: JDK (Java Development Kit): JRE + tools like compiler (javac), debugger, etc. If you want to WRITE
and COMPILE Java, install JDK.
✅ Tip: Remember this: JDK contains JRE, JRE contains JVM.
Q3. What are the features of Java?
• Object-Oriented: Everything is treated as objects (except primitives).
• Platform Independent: Bytecode runs on any OS via JVM.
• Simple: Syntax is similar to C/C++ but removes complex things like pointers.
• Secure: No direct memory access, strong type checking.
• Multithreaded: Can run multiple tasks at the same time.
• Robust: Strong memory management and exception handling.
1.2 Data Types, Variables & Operators
Q4. What are primitive data types in Java?
A: Java has 8 primitive data types. These are the most basic types, not objects.
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
byte → 1 byte → range: -128 to 127
short → 2 bytes → range: -32768 to 32767
int → 4 bytes → range: ~-2 billion to 2 billion (most used)
long → 8 bytes → very large numbers, use 'L' suffix: long x = 100L;
float → 4 bytes → decimal numbers, use 'f' suffix: float x = 3.14f;
double → 8 bytes → more precise decimal (default for decimals)
char → 2 bytes → single character: char c = 'A';
boolean → 1 bit → true or false only
✅ Tip: int and double are the most commonly used in interviews. Always remember their sizes.
Q5. What is the difference between == and .equals() in Java?
A: == checks if two variables point to the SAME memory location (reference comparison). .equals()
checks if the CONTENT (value) of two objects is the same.
String a = new String("hello");
String b = new String("hello");
[Link](a == b); // false (different objects in memory)
[Link]([Link](b)); // true (same content)
📌 Note: For String literals (not 'new'), Java reuses the same object from String Pool, so == might return
true. But always use .equals() for safe comparison.
Q6. What is type casting in Java?
A: Type casting means converting one data type to another.
A: Widening (automatic): Going from smaller to larger type. Java does this automatically.
int x = 10;
double y = x; // automatic widening, no data loss
A: Narrowing (manual): Going from larger to smaller type. You must cast explicitly and there can be data
loss.
double a = 9.99;
int b = (int) a; // b = 9 (decimal part is lost, not rounded)
1.3 Control Flow
Q7. Explain if-else, switch, for, while, do-while with example.
A: These are the basic control structures. Here is a quick reference:
// if-else
if (age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}
// switch
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
default: [Link]("Other");
}
// for loop
for (int i = 0; i < 5; i++) {
[Link](i);
}
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
// while loop (check condition first)
while (i < 5) { i++; }
// do-while (runs at least once, checks after)
do { i++; } while (i < 5);
Q8. What is the difference between break and continue?
A: break: Completely exits the loop. No more iterations happen.
A: continue: Skips the current iteration and moves to the next one.
for (int i = 0; i < 5; i++) {
if (i == 3) break; // stops at 3, prints 0 1 2
[Link](i + " ");
}
for (int i = 0; i < 5; i++) {
if (i == 3) continue; // skips 3, prints 0 1 2 4
[Link](i + " ");
}
SECTION 2: Object-Oriented Programming (OOP)
2.1 Core OOP Concepts
Q9. What are the four pillars of OOP?
A: Encapsulation: Wrapping data (variables) and methods together in a class and hiding internal details
using private access.
A: Inheritance: One class can use the properties and methods of another class using 'extends'. Promotes
code reuse.
A: Polymorphism: Same method name but different behavior. Two types: compile-time (method
overloading) and runtime (method overriding).
A: Abstraction: Hiding complex implementation and showing only what is necessary. Done via abstract
classes or interfaces.
✅ Tip: In every interview, you will be asked to explain OOP with real-life examples. Use Car, Animal, or
BankAccount examples.
Q10. What is a class and object in Java?
A: A class is a blueprint or template. An object is an actual instance created from that blueprint.
// Class is the blueprint
class Car {
String color; // attribute
int speed;
void drive() { // method
[Link]("Car is driving");
}
}
// Object is a real instance
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
Car myCar = new Car(); // 'new' creates object in heap memory
[Link] = "Red";
[Link]();
2.2 Encapsulation
Q11. What is Encapsulation? How do you achieve it in Java?
A: Encapsulation means keeping your data safe inside a class by making variables private, and providing
public getter/setter methods to access them.
class BankAccount {
private double balance; // hidden, cannot be accessed directly
// Getter: to read value
public double getBalance() {
return balance;
}
// Setter: to set value with validation
public void setBalance(double amount) {
if (amount >= 0) {
[Link] = amount;
}
}
}
📌 Note: 'this' keyword refers to the current object. It is used when the variable name and parameter name
are the same.
2.3 Inheritance
Q12. What is Inheritance? What are its types?
A: Inheritance allows a child class to inherit (reuse) properties and methods of a parent class. Java uses
the 'extends' keyword.
class Animal {
void eat() { [Link]("Animal eats"); }
}
class Dog extends Animal { // Dog inherits from Animal
void bark() { [Link]("Dog barks"); }
}
Dog d = new Dog();
[Link](); // works! inherited from Animal
[Link](); // Dog's own method
A: Types: Single (A extends B), Multilevel (A extends B, B extends C), Hierarchical (B and C both extend
A). Java does NOT support multiple inheritance with classes (to avoid Diamond Problem) but supports it
through interfaces.
Q13. What is the super keyword?
A: 'super' is used to refer to the parent class. It has three uses:
• [Link] — access parent's variable
• [Link]() — call parent's method
• super() — call parent's constructor (must be first line in child constructor)
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
class Animal {
String name;
Animal(String name) { [Link] = name; }
void sound() { [Link]("Some sound"); }
}
class Dog extends Animal {
Dog(String name) {
super(name); // calls Animal's constructor
}
void sound() {
[Link](); // calls Animal's sound()
[Link]("Woof!");
}
}
2.4 Polymorphism
Q14. What is the difference between method overloading and overriding?
A: Method Overloading (Compile-time Polymorphism): Same method name, different parameters (type or
count), in the SAME class.
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // overloaded
int add(int a, int b, int c) { return a + b + c; } // also overloaded
}
A: Method Overriding (Runtime Polymorphism): Child class provides its own version of a method already
defined in parent class. Same name, same parameters.
class Animal {
void sound() { [Link]("Generic sound"); }
}
class Cat extends Animal {
@Override
void sound() { [Link]("Meow"); } // overriding
}
📌 Note: @Override annotation is optional but good practice. It helps compiler catch typos in method names.
Q15. What is runtime polymorphism and upcasting?
A: When a parent class reference variable holds a child class object, and the method called is decided at
runtime based on the actual object type, it is called runtime polymorphism.
Animal a = new Cat(); // upcasting: parent ref = child object
[Link](); // prints 'Meow' NOT 'Generic sound'
// JVM checks actual object type at runtime
✅ Tip: This is one of the most important interview topics. Practice with 2-3 examples.
2.5 Abstraction
Q16. What is an abstract class? How is it different from a normal class?
A: An abstract class cannot be instantiated (you cannot create its object with 'new'). It can have abstract
methods (no body) that must be implemented by child classes. It can also have regular methods with
implementation.
abstract class Shape {
abstract double area(); // no body, child MUST implement this
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
void display() { // regular method with body
[Link]("This is a shape");
}
}
class Circle extends Shape {
double radius;
Circle(double r) { [Link] = r; }
double area() { return 3.14 * radius * radius; } // must implement
}
// Shape s = new Shape(); // ERROR: cannot instantiate abstract class
Shape s = new Circle(5); // OK: upcasting
Q17. What is an Interface in Java?
A: An interface is a 100% abstract contract. All methods are abstract by default (before Java 8). A class
implements an interface using 'implements'. One class can implement multiple interfaces (solving the
multiple inheritance problem).
interface Flyable {
void fly(); // public abstract by default
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable { // multiple interfaces
public void fly() { [Link]("Duck flies"); }
public void swim() { [Link]("Duck swims"); }
}
📌 Note: From Java 8, interfaces can have 'default' and 'static' methods with body. From Java 9, they can
have 'private' methods too.
Q18. What is the difference between abstract class and interface?
Feature Abstract Class Interface
Can have constructor Yes No
Multiple inheritance No Yes (multiple interfaces)
Variables Can have any type public static final only
Methods Abstract + concrete Abstract (+ default from Java 8)
Speed Slightly faster Slightly slower
When to use Related classes with shared code Unrelated classes need same
behavior
SECTION 3: Constructors, Keywords & Access
Modifiers
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
3.1 Constructors
Q19. What is a constructor? What are its types?
A: A constructor is a special method called automatically when an object is created. It has the same name
as the class and no return type.
A: Default Constructor: No parameters. Java provides one if you don't write any.
A: Parameterized Constructor: Takes parameters to initialize object with specific values.
A: Copy Constructor: Takes another object as parameter and copies its data.
class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
// Parameterized constructor
Student(String name, int age) {
[Link] = name;
[Link] = age;
}
// Copy constructor
Student(Student s) {
[Link] = [Link];
[Link] = [Link];
}
}
Q20. What is constructor chaining using this() and super()?
A: this() calls another constructor in the SAME class. super() calls the parent class constructor. Both must
be the first statement in the constructor.
class Employee {
String name;
int id;
double salary;
Employee(String name) {
this(name, 0); // calls Employee(String, int)
}
Employee(String name, int id) {
this(name, id, 50000.0); // calls Employee(String, int, double)
}
Employee(String name, int id, double salary) {
[Link] = name;
[Link] = id;
[Link] = salary;
}
}
3.2 Important Keywords
Q21. What is the static keyword in Java?
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
A: static means the member belongs to the CLASS, not to any specific object. You can access it without
creating an object.
class Counter {
static int count = 0; // shared by all objects
Counter() {
count++; // each new object increments the same count
}
static void showCount() { // static method
[Link]("Count: " + count);
}
}
[Link](); // no object needed
📌 Note: Static methods cannot use 'this' or access non-static variables directly. They don't have access to
instance-level things.
Q22. What is the final keyword in Java?
A: final has three uses depending on where it is applied:
• final variable: Value cannot be changed (acts like a constant). Ex: final int MAX = 100;
• final method: Cannot be overridden by child class.
• final class: Cannot be extended (no inheritance). Ex: String class in Java is final.
Q23. What is the difference between final, finally, and finalize?
A: final: keyword — prevents change/inheritance/override.
A: finally: block in exception handling — code inside always runs whether exception occurs or not.
A: finalize(): method called by Garbage Collector before destroying an object. Not recommended to use
(deprecated in Java 9+).
✅ Tip: This is a classic trick question in interviews. All three sound similar but are completely different
things.
3.3 Access Modifiers
Q24. What are the access modifiers in Java? Explain each.
A: Access modifiers control who can access a class, method, or variable.
Modifier Same Class Same Package Subclass Everywhere
private ✅ ❌ ❌ ❌
default (no ✅ ✅ ❌ ❌
keyword)
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅
SECTION 4: Strings in Java
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
4.1 String Basics
Q25. What is a String in Java? Is it a primitive or object?
A: String is not a primitive data type. It is a class in Java ([Link]). When you write String s =
"hello", Java stores it in a special area called the String Pool (inside Heap memory) for memory efficiency.
Q26. What is the String Pool? Why does it exist?
A: String Pool is a special area in Heap memory where Java stores unique string literals. When you create
a string literal, Java first checks the pool. If the same value already exists, it reuses it instead of creating a
new object. This saves memory.
String a = "hello"; // stored in String Pool
String b = "hello"; // points to SAME object in pool
[Link](a == b); // true (same reference!)
String c = new String("hello"); // forces new object in Heap
[Link](a == c); // false (different object)
Q27. What is the difference between String, StringBuilder, and StringBuffer?
A: String: Immutable. Every time you modify it, a new object is created in memory. Slow for repeated
modifications.
A: StringBuilder: Mutable. You can change it without creating new objects. NOT thread-safe. Use when
single thread is working.
A: StringBuffer: Mutable and thread-safe (synchronized). Slightly slower than StringBuilder. Use in multi-
threaded code.
String s = "Hello";
s = s + " World"; // creates NEW object, old one becomes garbage
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // modifies SAME object, faster
[Link]([Link]());
✅ Tip: In interviews: use StringBuilder for string manipulation inside loops. Never use String concatenation
in a loop.
Q28. What are some important String methods? Give examples.
String s = "Hello World";
[Link]() // 11 — number of characters
[Link](0) // 'H' — character at index 0
[Link]('o') // 4 — first occurrence of 'o'
[Link](6) // "World" — from index 6 to end
[Link](0, 5) // "Hello" — index 0 to 4
[Link]() // "hello world"
[Link]() // "HELLO WORLD"
[Link]() // removes leading/trailing spaces
[Link]('l','r') // "Herro Worrd"
[Link]("World") // true
[Link]("He") // true
[Link](" ") // ["Hello", "World"]
[Link]("Hello World") // true
[Link]("hello world") // true
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
SECTION 5: Arrays & Collections Framework
5.1 Arrays
Q29. What is an array in Java? How do you declare and use it?
A: An array is a fixed-size collection of elements of the same type stored in contiguous memory.
// Declaration + initialization
int[] arr = new int[5]; // creates array of size 5, all zeros
arr[0] = 10;
arr[1] = 20;
// Direct initialization
int[] numbers = {1, 2, 3, 4, 5};
// 2D array
int[][] matrix = new int[3][3];
int[][] grid = {{1,2,3}, {4,5,6}, {7,8,9}};
// Iterate using enhanced for loop
for (int num : numbers) {
[Link](num + " ");
}
📌 Note: Arrays in Java are objects. [Link] gives the size. Index starts at 0. Accessing out-of-bound index
throws ArrayIndexOutOfBoundsException.
5.2 Collections Framework
Q30. What is the Collections Framework in Java?
A: Collections Framework is a set of classes and interfaces for storing and manipulating groups of data.
The main ones you need for interviews are: ArrayList, LinkedList, HashMap, HashSet, and Stack.
Q31. What is the difference between ArrayList and LinkedList?
A: Both implement the List interface. The difference is in internal structure and performance:
ArrayList: backed by array → fast GET by index (O(1))
slow INSERT/DELETE in middle (shifting needed)
LinkedList: backed by nodes → fast INSERT/DELETE anywhere (O(1))
slow GET by index (O(n) — must traverse from start)
// ArrayList usage
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link](0); // "Apple"
[Link]("Apple");
[Link](); // 1
// Iterate
for (String fruit : list) {
[Link](fruit);
}
✅ Tip: For interviews: Use ArrayList when you need frequent access. Use LinkedList when you need
frequent add/remove at beginning or end.
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
Q32. What is HashMap? How does it work?
A: HashMap stores data as key-value pairs. Each key must be unique. It uses hashing to store and
retrieve values in O(1) average time. It allows one null key and multiple null values.
HashMap<String, Integer> map = new HashMap<>();
[Link]("Alice", 90);
[Link]("Bob", 85);
[Link]("Alice", 95); // overwrites previous value for key "Alice"
[Link]("Bob"); // 85
[Link]("Alice"); // true
[Link]("Bob");
[Link](); // 1
// Iterate over all entries
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}
Q33. What is the difference between HashMap, LinkedHashMap, and TreeMap?
• HashMap: No guaranteed order. Fastest (O(1) operations).
• LinkedHashMap: Maintains insertion order. Slightly slower than HashMap.
• TreeMap: Maintains sorted (natural) order of keys. Slower (O(log n) operations). Uses Red-Black tree
internally.
✅ Tip: If asked about order in maps, say LinkedHashMap for insertion order and TreeMap for sorted order.
Q34. What is the difference between HashSet and TreeSet?
A: HashSet: Stores unique elements. No order guaranteed. Uses hashing. O(1) add/remove/search.
A: TreeSet: Stores unique elements in sorted (ascending) order. Uses Red-Black tree. O(log n)
operations.
HashSet<Integer> set = new HashSet<>();
[Link](5);
[Link](2);
[Link](8);
[Link](2); // duplicate, ignored
[Link](set); // [2, 5, 8] or any order
SECTION 6: Exception Handling
6.1 Exception Basics
Q35. What is an exception? What is the difference between Error and Exception?
A: An exception is an unexpected event that occurs during program execution and disrupts normal flow.
A: Error: Serious problem that program CANNOT handle. Example: OutOfMemoryError,
StackOverflowError. You should not try to catch these.
A: Exception: Problem that program CAN handle. Example: NullPointerException,
ArrayIndexOutOfBoundsException. You should catch and handle these.
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
Q36. What is the difference between checked and unchecked exceptions?
A: Checked Exceptions: Checked at compile time. You MUST handle them or declare them with 'throws'.
Examples: IOException, SQLException, FileNotFoundException.
A: Unchecked Exceptions: Occur at runtime. Compiler doesn't force you to handle them. Examples:
NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.
📌 Note: All checked exceptions extend Exception (but not RuntimeException). All unchecked exceptions
extend RuntimeException.
Q37. Explain try-catch-finally with example.
try {
// Code that might throw exception
int result = 10 / 0; // throws ArithmeticException
[Link](result);
} catch (ArithmeticException e) {
// Handle the specific exception
[Link]("Error: " + [Link]());
} catch (Exception e) {
// Catch-all for any other exception
[Link]("Something went wrong: " + e);
} finally {
// This ALWAYS runs, exception or not
[Link]("This always executes");
}
📌 Note: Multiple catch blocks must go from specific to general. Put ArithmeticException before Exception.
Otherwise compiler error.
Q38. What is the difference between throw and throws?
A: throw: Used inside a method body to manually throw an exception object.
A: throws: Used in method signature to declare that this method might throw an exception (caller must
handle it).
// throws in signature
void readFile(String path) throws IOException {
if (path == null) {
throw new IllegalArgumentException("Path cannot be null"); // throw
}
// file reading code...
}
Q39. What is a custom exception? How do you create one?
A: You can create your own exception by extending Exception (checked) or RuntimeException
(unchecked).
// Custom checked exception
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
double balance = 1000;
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
throw new InsufficientFundsException("Not enough balance!");
}
balance -= amount;
}
}
SECTION 7: Java 8+ Important Features
7.1 Lambda Expressions
Q40. What is a Lambda Expression in Java 8?
A: A lambda expression is a short way to write anonymous functions (a method without a name). It is used
mainly with functional interfaces (interfaces with exactly one abstract method).
// Old way (anonymous class)
Runnable r1 = new Runnable() {
@Override
public void run() {
[Link]("Running!");
}
};
// Lambda way (clean and short)
Runnable r2 = () -> [Link]("Running!");
// Lambda with parameter
List<Integer> nums = [Link](3, 1, 4, 1, 5);
[Link](n -> [Link](n));
// Lambda with multiple lines
[Link](n -> {
if (n > 2) [Link](n);
});
7.2 Stream API
Q41. What is the Stream API? Give examples of common operations.
A: Stream API lets you process collections of data in a functional, declarative way. It does NOT store data
— it just processes it. Key operations are filter, map, collect, reduce, sorted, distinct, count.
List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8);
// Filter: keep only even numbers
List<Integer> evens = [Link]()
.filter(n -> n % 2 == 0)
.collect([Link]()); // [2, 4, 6, 8]
// Map: square each number
List<Integer> squares = [Link]()
.map(n -> n * n)
.collect([Link]()); // [1, 4, 9, 16...]
// Filter + Map + Collect
List<String> names = [Link]("Alice", "Bob", "Charlie", "Anna");
List<String> result = [Link]()
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
.filter(name -> [Link]("A"))
.map(String::toUpperCase)
.sorted()
.collect([Link]()); // [ALICE, ANNA]
// Reduce: sum of all numbers
int sum = [Link]()
.reduce(0, (a, b) -> a + b); // 36
7.3 Optional
Q42. What is Optional in Java 8? Why is it used?
A: Optional is a container object that may or may not contain a non-null value. It helps avoid
NullPointerException. Instead of returning null from a method, return an Optional.
Optional<String> opt1 = [Link]("Hello");
Optional<String> opt2 = [Link]();
Optional<String> opt3 = [Link](null); // safe — won't throw
[Link](); // true
[Link](); // "Hello"
[Link](); // false
[Link]("Default"); // returns "Default" if empty
[Link](s -> [Link]([Link]())); // 5
SECTION 8: Multithreading & Concurrency
8.1 Thread Basics
Q43. What is a Thread in Java? How do you create one?
A: A thread is a lightweight sub-process — the smallest unit of execution. Java supports multithreading,
meaning multiple threads can run concurrently. Two ways to create threads:
A: Way 1: Extend Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread running: " + [Link]().getName());
}
}
MyThread t = new MyThread();
[Link](); // IMPORTANT: use start(), not run()
A: Way 2: Implement Runnable interface (preferred)
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable running");
}
}
Thread t = new Thread(new MyRunnable());
[Link]();
📌 Note: Always call start() not run(). Calling run() directly just executes on the current thread — no new
thread is created.
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
Q44. What is the lifecycle of a Thread?
• New: Thread is created but not started.
• Runnable: After start() is called. Thread is ready to run.
• Running: Thread is actually executing.
• Blocked/Waiting: Thread is waiting for a resource or another thread.
• Terminated: Thread finished execution.
Q45. What is synchronized in Java? Why is it needed?
A: When multiple threads access shared data at the same time, they can corrupt it. synchronized ensures
only one thread can execute a method or block at a time.
class Counter {
int count = 0;
synchronized void increment() { // only one thread at a time
count++;
}
}
✅ Tip: Race condition: when two threads modify the same data and result depends on timing. synchronized
solves this.
Q46. What is deadlock? How to avoid it?
A: Deadlock occurs when two or more threads are waiting for each other's locks forever, and none of
them can proceed. Thread A holds Lock 1 and waits for Lock 2. Thread B holds Lock 2 and waits for Lock
1. Both are stuck.
A: How to avoid: Always acquire locks in the same fixed order in all threads. Use tryLock() with timeout.
Keep synchronized blocks small. Use higher-level concurrency utilities from [Link].
SECTION 9: Memory Management & Garbage Collection
Q47. How does memory management work in Java?
A: Java divides memory into two main areas:
• Stack Memory: Stores method calls and local variables. Each thread has its own stack. Memory is freed
automatically when method returns. LIFO structure.
• Heap Memory: Stores all objects created with 'new'. Shared by all threads. Garbage Collector manages
this memory.
void method() {
int x = 5; // x stored in Stack
String s = new String("hello"); // s (reference) in Stack
// actual String object in Heap
}
Q48. What is Garbage Collection in Java?
A: Garbage Collection (GC) is the automatic process of finding and freeing objects in Heap memory that
are no longer referenced by any variable. You don't need to manually free memory like in C/C++.
A: An object becomes eligible for GC when no variable points to it. You can suggest GC to run using
[Link]() but it is not guaranteed.
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
📌 Note: GC runs in background. You cannot force it. You cannot predict exactly when it runs. This is by
design for safety.
SECTION 10: Design Patterns (Advanced)
Q49. What is Singleton design pattern? Write the code.
A: Singleton ensures only ONE instance of a class is created throughout the program. Used for database
connections, config managers, logging.
class Singleton {
private static Singleton instance; // single instance
private Singleton() {} // private constructor — no one can 'new' it
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton(); // create only if not exists
}
return instance;
}
}
// Usage
Singleton s1 = [Link]();
Singleton s2 = [Link]();
[Link](s1 == s2); // true — same object
📌 Note: Thread-safe Singleton: add 'synchronized' to getInstance() method or use double-checked locking.
Ask if interviewer wants thread-safe version.
Q50. What is the Factory design pattern?
A: Factory pattern creates objects without exposing the creation logic. The client says 'give me an Animal'
and the factory decides which specific Animal to create based on input.
interface Animal {
void speak();
}
class Dog implements Animal {
public void speak() { [Link]("Woof"); }
}
class Cat implements Animal {
public void speak() { [Link]("Meow"); }
}
class AnimalFactory {
public static Animal create(String type) {
if ([Link]("Dog")) return new Dog();
if ([Link]("Cat")) return new Cat();
throw new IllegalArgumentException("Unknown animal: " + type);
}
}
Animal a = [Link]("Dog");
[Link](); // Woof
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
SECTION 11: Generics
Q51. What are Generics in Java? Why use them?
A: Generics allow you to write classes and methods that work with any data type, while maintaining type
safety at compile time. Without generics, you would use Object type everywhere and need explicit casting
which can fail at runtime.
// Without generics — unsafe
ArrayList list = new ArrayList();
[Link]("hello");
String s = (String) [Link](0); // explicit cast needed, can throw ClassCastException
// With generics — type safe
ArrayList<String> names = new ArrayList<>();
[Link]("hello");
String name = [Link](0); // no cast needed, compiler checks type
// Generic method
public <T> void printArray(T[] array) {
for (T element : array) {
[Link](element + " ");
}
}
SECTION 12: Common Coding Questions in Interviews
Q52. Reverse a String in Java.
// Method 1: Using StringBuilder
String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
// Method 2: Using loop (if they ask manual approach)
String reverse(String s) {
String result = "";
for (int i = [Link]() - 1; i >= 0; i--) {
result += [Link](i);
}
return result;
}
Q53. Check if a String is a Palindrome.
boolean isPalindrome(String s) {
String reversed = new StringBuilder(s).reverse().toString();
return [Link](reversed);
}
// isPalindrome("racecar") → true
// isPalindrome("hello") → false
Q54. Find duplicate elements in an array.
void findDuplicates(int[] arr) {
HashSet<Integer> seen = new HashSet<>();
for (int num : arr) {
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
if () { // add returns false if already present
[Link]("Duplicate: " + num);
} else {
[Link](num);
}
}
}
Q55. Fibonacci series using recursion and iteration.
// Iterative (preferred in interviews — O(n))
void fibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
[Link](a + " ");
int temp = a + b;
a = b;
b = temp;
}
}
// Recursive (clean but slow for large n — O(2^n))
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
Q56. Swap two numbers without a third variable.
int a = 5, b = 10;
// Method 1: Using arithmetic
a = a + b; // a = 15
b = a - b; // b = 5
a = a - b; // a = 10
// Method 2: Using XOR
a = a ^ b;
b = a ^ b;
a = a ^ b;
Q57. Sort an ArrayList in Java.
ArrayList<Integer> list = new ArrayList<>([Link](5, 2, 8, 1, 9));
[Link](list); // ascending: [1, 2, 5, 8, 9]
[Link](list, [Link]()); // descending: [9, 8, 5, 2, 1]
// Sort custom objects using Comparator
[Link]((a, b) -> a - b); // ascending using lambda
SECTION 13: Quick Revision Cheat Sheet
☕ Java Interview Notes | Beginner to Advanced | Placement Ready
Key Differences at a Glance
Topic Option A Option B
Abstract class vs Can have constructors, partial impl No constructor, all abstract (pre-Java
Interface 8)
== vs .equals() Checks reference/memory address Checks actual value/content
throw vs throws Used inside method to throw Used in signature to declare
checked vs unchecked Compile-time, must handle Runtime, optional
(IOException) (NullPointerException)
ArrayList vs LinkedList Fast get O(1), slow insert/delete Slow get O(n), fast insert/delete
HashMap vs TreeMap No order, O(1) Sorted order, O(log n)
String vs StringBuilder Immutable, slow for concat Mutable, fast for concat
Overloading vs Same class, different params Child class, same signature
Overriding
Stack vs Heap Local vars, thread-specific, LIFO Objects, shared, GC managed
final vs finally vs finalize Keyword: no change Block: always runs / Method: before
GC
Most Commonly Asked Interview Topics (by Companies)
• TCS, Infosys, Wipro (Service): OOP concepts, String methods, exception handling, basic collection
classes, difference questions.
• Capgemini, Cognizant: Collections, multithreading basics, design patterns, Java 8 features.
• Accenture, HCL: Core Java, JDBC, threads, generics, basic data structures.
• Product companies (Startup/Mid-level): Streams, Lambdas, concurrency, design patterns, coding rounds
(DSA in Java).
• FAANG-level: Advanced multithreading, memory model, JVM internals, complex DSA, system design.
Good luck with your placement drive! You got this. ☕
Practice code daily. Read error messages carefully. Explain your thought process in interviews.