Singleton, Immutable & Wrapper
Singleton pattern, immutable classes, wrapper classes, autoboxing
- Implement thread-safe Singleton patterns
- Design immutable classes following best practices
- Master wrapper classes and autoboxing/unboxing
*Java Basics to Advanced | Lecture Classes Part 4*
Table of Contents
- What is a Singleton?
- Method 1: Eager Initialization
- Method 2: Lazy Initialization
- Method 3: Synchronized Method
- Method 4: Double-Checked Locking
- The Memory Issue — Why
volatileis Required - Method 5: Bill Pugh Solution (Static Nested Class)
- Method 6: Enum Singleton
- Singleton Methods Comparison
- What is an Immutable Class?
- Rules for Creating Immutable Classes
- The Collection Trap — Defensive Copying
- Complete Immutable Class Example
- Wrapper Classes
- Summary Diagrams
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Quick Revision Summary
1. Singleton Class
1.1 What is a Singleton?
Definition
A Singleton class is a class that allows only one object (instance) to be created for its entire lifetime, regardless of how many times or from how many places it is instantiated.
The name says it all — singleton = single instance.
Why Does Singleton Exist?
There are many real-world scenarios where creating multiple instances of a class would be wasteful, incorrect, or dangerous. The classic example is a database connection:
1Application2 │3 ├── Class A ──── new DBConnection() ──┐4 ├── Class B ──── new DBConnection() ──┼──► 3 separate connections to DB ← WASTEFUL5 └── Class C ──── new DBConnection() ──┘6
7With Singleton:8Application9 │10 ├── Class A ──── DBConnection.getInstance() ──┐11 ├── Class B ──── DBConnection.getInstance() ──┼──► ONE shared connection ✅12 └── Class C ──── DBConnection.getInstance() ──┘Setting up a database connection is expensive (network handshake, authentication, resource allocation). You want to do it once and reuse that connection everywhere.
Other Real-World Use Cases
| Use Case | Why Singleton? |
|---|---|
| Database connection pool | Expensive to create; share one pool |
| Logger | All parts of app write to same log |
| Configuration manager | One source of truth for app config |
| Thread pool | Shared pool of worker threads |
| Cache | One shared in-memory cache |
| Registry / Service locator | Central registry of services |
The Six Singleton Patterns
1.2 Method 1: Eager Initialization
Concept
Eager initialization
creates the singleton object at class loading time — before anyone has even asked for it.
The word eager means "in advance, without waiting."
Implementation
1public class DBConnection {2
3 // Step 1: Create the object eagerly — at class load time4 // private: nobody outside can access this directly5 // static: belongs to the CLASS, not to any object — only ONE copy ever exists6 private static DBConnection connObject = new DBConnection();7
8 // Step 2: Make constructor private — prevents 'new DBConnection()' from outside9 private DBConnection() {10 System.out.println("DBConnection created");11 }12
13 // Step 3: Public static method to return the single instance14 // static: can be called via class name without creating an object15 public static DBConnection getInstance() {16 return connObject;17 }18}How to Use It
1public class Application {2 public static void main(String[] args) {3
4 DBConnection conn1 = DBConnection.getInstance();5 DBConnection conn2 = DBConnection.getInstance();6 DBConnection conn3 = DBConnection.getInstance();7
8 // All three references point to the SAME object9 System.out.println(conn1 == conn2); // true10 System.out.println(conn2 == conn3); // true11
12 // This would be a COMPILE ERROR — constructor is private13 // DBConnection conn4 = new DBConnection(); // ❌14 }15}DBConnection created ← printed only ONCE, at class load time true true
Three Key Design Decisions Explained
◆ Why `private static` for the object?
1private static DBConnection connObject = new DBConnection();private→ Nobody outside the class can access or reassignconnObjectstatic→ Belongs to the class, not to any instance. No matter how many timesgetInstance()is called, there is only oneconnObject— it is a class-level variable
◆ Why `private` constructor?
1private DBConnection() { }Without a private constructor, anyone could do:
1DBConnection c = new DBConnection(); // Creates a SECOND object — breaks singleton!Making the constructor private means only code inside DBConnection itself can call new DBConnection().
◆ Why `public static` for `getInstance()`?
1public static DBConnection getInstance() { return connObject; }public→ Anyone can call itstatic→ Can be called without an object:DBConnection.getInstance(). This is essential — if it were non-static, you'd need an object to call it, which defeats the purpose.
Advantages and Disadvantages
| Detail | |
|---|---|
| ✅ Simple | Easy to implement and understand |
| ✅ Thread-safe | Object is created at class load time — before any thread can use it |
| ❌ Wastes memory | Object is created even if the application never uses it |
1.3 Method 2: Lazy Initialization
Concept
Lazy initialization
delays creating the singleton object until the first time it is actually needed.
The word lazy means "don't do work until you have to."
Implementation
1public class DBConnection {2
3 // Object NOT created yet — null initially4 private static DBConnection connObject = null;5
6 private DBConnection() { }7
8 public static DBConnection getInstance() {9 // Create object ONLY if it doesn't exist yet10 if (connObject == null) {11 connObject = new DBConnection(); // Created on first call only12 }13 return connObject;14 }15}How It Works (Single Thread)
1First call: getInstance() → connObject is null → CREATE new object → return it2Second call: getInstance() → connObject is NOT null → return existing object3Third call: getInstance() → connObject is NOT null → return existing objectThe Thread-Safety Problem
Lazy initialization has a critical flaw in multi-threaded environments:
1Thread 1: checks connObject == null → TRUE (object not yet created)2Thread 2: checks connObject == null → TRUE (object not yet created — same time!)3Thread 1: creates new DBConnection() and assigns to connObject4Thread 2: also creates new DBConnection() and assigns to connObject ← SECOND OBJECT!Both threads read null simultaneously, both enter the if block, and two objects are created — breaking the singleton guarantee.
Advantages and Disadvantages
| Detail | |
|---|---|
| ✅ Memory efficient | Object created only when needed |
| ❌ Not thread-safe | Two threads can create two objects simultaneously |
1.4 Method 3: Synchronized Method
Concept
Adding the synchronized keyword to getInstance() ensures that only one thread can execute the method at a time, preventing the race condition.
Implementation
1public class DBConnection {2
3 private static DBConnection connObject = null;4
5 private DBConnection() { }6
7 // synchronized: only ONE thread can be inside this method at a time8 public static synchronized DBConnection getInstance() {9 if (connObject == null) {10 connObject = new DBConnection();11 }12 return connObject;13 }14}How Synchronization Works
1Thread 1 enters getInstance() → acquires LOCK → checks null → creates object → releases LOCK2Thread 2 tries to enter → BLOCKED (waiting for lock)3Thread 2 gets lock → checks null → object exists → returns it → releases LOCKThe synchronized keyword ensures mutual exclusion — only one thread inside at a time.
The Performance Problem
While synchronized solves thread safety, it creates a performance bottleneck:
1// Every single call to getInstance() acquires and releases a lock2// Even when the object is ALREADY created and we just need to return it!3
4Place 1: getInstance() → LOCK → check null? No → return → UNLOCK (unnecessary!)5Place 2: getInstance() → LOCK → check null? No → return → UNLOCK (unnecessary!)6Place 3: getInstance() → LOCK → check null? No → return → UNLOCK (unnecessary!)7// ... called 1000 times → 1000 lock/unlock operations → VERY SLOWAfter the object is created, the null check always fails and we just return the existing object. There is no need for synchronization at this point — yet the lock is acquired every single time.
getInstance() a performance bottleneck. This approach is not recommended for production use.Advantages and Disadvantages
| Detail | |
|---|---|
| ✅ Thread-safe | Synchronized prevents concurrent object creation |
| ❌ Very slow | Lock/unlock on every call, even after object is created |
| ❌ Bottleneck | All threads queue up for the lock |
1.5 Method 4: Double-Checked Locking
Concept
Double-Checked Locking (DCL)
optimizes the synchronized approach by only acquiring the lock when the object does not yet exist. Once created, threads skip the lock entirely.
The name comes from checking the null condition twice — once outside the lock, once inside.
Implementation
1public class DBConnection {2
3 // volatile is CRITICAL — explained in detail below4 private static volatile DBConnection connObject = null;5
6 private DBConnection() { }7
8 public static DBConnection getInstance() {9
10 // CHECK 1: If object exists, skip synchronization entirely (fast path)11 if (connObject == null) {12
13 // Only synchronize when object doesn't exist yet14 synchronized (DBConnection.class) {15
16 // CHECK 2: Re-check inside lock (another thread may have created it)17 if (connObject == null) {18 connObject = new DBConnection();19 }20 }21 }22 return connObject;23 }24}Why Two Checks?
◆ Check 1 (outside lock): Performance Gate
1If object already exists → skip the lock entirely → just return itThis is the "fast path" — once the object is created, the vast majority of calls never enter the synchronized block.
◆ Check 2 (inside lock): Safety Gate
1Thread 1: passes Check 1 (null), waits for lock2Thread 2: passes Check 1 (null), gets lock, creates object, releases lock3Thread 1: gets lock now — checks again (Check 2) → object exists! → does NOT create anotherWithout Check 2, two threads could both pass Check 1 simultaneously and both create objects. The inner check prevents this.
Execution Flow
Performance Comparison
1Synchronized Method:2 Every call: LOCK → check → return → UNLOCK (1000 calls = 1000 locks)3
4Double-Checked Locking (after object created):5 Every call: check → return (1000 calls = 0 locks) ✅1.6 The Memory Issue Why `volatile` is Required
Background: CPU Caches (L1 Cache)
Modern CPUs have multiple cores, each with their own L1 cache (a small, ultra-fast memory buffer). For performance, each core reads/writes data from its own cache rather than from main memory (RAM). Periodically, caches are synchronized with main memory.
1┌─────────────────────────────────────────────┐2│ CPU │3│ ┌──────────────┐ ┌──────────────┐ │4│ │ Core 1 │ │ Core 2 │ │5│ │ ┌────────┐ │ │ ┌────────┐ │ │6│ │ │L1 Cache│ │ │ │L1 Cache│ │ │7│ │ └────────┘ │ │ └────────┘ │ │8│ └──────────────┘ └──────────────┘ │9│ ↕ (periodic sync) ↕ │10│ ┌─────────────────────┐ │11│ │ Main Memory │ │12│ │ (RAM / Heap) │ │13│ └─────────────────────┘ │14└─────────────────────────────────────────────┘Problem 1: Visibility (Cache Not Synced)
1Thread 1 runs on Core 1:2 - Acquires lock3 - Creates new DBConnection()4 - Assigns connObject = new DBConnection()5 - Stores result in Core 1's L1 CACHE (not yet synced to main memory)6 - Releases lock7
8Thread 2 runs on Core 2:9 - Checks connObject == null10 - Reads from main memory (or Core 2's cache)11 - Main memory is NOT yet updated (Core 1 hasn't synced)12 - Sees connObject == null ← STALE VALUE13 - Creates ANOTHER object! ← BUG: two objects existThe cache sync between cores is not instantaneous. Thread 2 reads a stale null from memory before Core 1's cache has been flushed.
Problem 2: Instruction Reordering
The JVM and CPU are allowed to reorder instructions for performance, as long as the result appears the same in a single-threaded context. But this can break multi-threaded assumptions.
The line connObject = new DBConnection() is not atomic — it compiles to roughly:
- Allocate memory for a
DBConnectionobject - Call constructor to initialize the object
- Assign the memory address to
connObject
The JVM may reorder steps 2 and 3:
- Allocate memory
- Assign memory address to
connObject← reordered! - Call constructor
Now another thread could see connObject != null (step 2 done) but the object is not yet fully initialized (step 3 not done). Accessing this half-initialized object causes unpredictable behavior.
Solution: `volatile`
Thevolatilekeyword guarantees two things: 1. Visibility — all reads and writes to the variable go directly to/from main memory, bypassing the CPU cache 2. Ordering — prevents instruction reordering around the volatile write
1private static volatile DBConnection connObject = null;2// ↑ volatileWith volatile:
- When Thread 1 writes to
connObject, it writes directly to main memory (not just L1 cache) - When Thread 2 reads
connObject, it reads directly from main memory (not from its own stale cache) - The constructor is guaranteed to complete before the reference is written to
connObject
1Without volatile:2 Thread 1 writes connObject → L1 Cache (not yet in main memory) → Thread 2 reads null from memory → BUG3
4With volatile:5 Thread 1 writes connObject → directly to main memory → Thread 2 reads correct value → ✅volatile is broken in Java's memory model. Always use volatile with DCL. Most interviews will specifically ask about this.Advantages and Disadvantages of DCL
| Detail | |
|---|---|
| ✅ Thread-safe | Double check + synchronization prevents race conditions |
| ✅ Faster than synchronized method | Lock only acquired during creation, not on every call |
| ❌ Complex | Easy to implement incorrectly (forgetting volatile) |
| ❌ Still uses lock | synchronized and volatile still have some overhead |
1.7 Method 5: Bill Pugh Solution (Static Nested Class)
Concept
The Bill Pugh Solution cleverly uses a private static nested class to hold the singleton instance. The nested class is loaded only when it is first referenced — providing lazy initialization without any synchronization.
This exploits a fundamental property of Java class loading:
A nested class is not loaded into memory when the outer class is loaded. It is loaded only when it is first accessed/used.
Implementation
1public class DBConnection {2
3 // Constructor private — prevents external instantiation4 private DBConnection() { }5
6 // Private static nested class — holds the singleton instance7 // This class is NOT loaded until getInstance() is first called8 private static class DBConnectionHelper {9 // Eager initialization inside the nested class10 // But since the class is loaded lazily, this is effectively lazy too11 private static final DBConnection INSTANCE = new DBConnection();12 }13
14 // When this method is called for the FIRST TIME:15 // → JVM loads DBConnectionHelper16 // → DBConnectionHelper's static field is initialized (object created)17 // → INSTANCE is returned18 // Subsequent calls:19 // → DBConnectionHelper is already loaded → INSTANCE already exists → return it20 public static DBConnection getInstance() {21 return DBConnectionHelper.INSTANCE;22 }23}How It Solves Eager Initialization's Problem
1Application starts:2 → DBConnection class is loaded3 → DBConnectionHelper is NOT loaded yet (nested class — deferred)4 → No object created yet ✅ (lazy)5
6First call to DBConnection.getInstance():7 → JVM references DBConnectionHelper.INSTANCE8 → JVM loads DBConnectionHelper for the first time9 → Static field INSTANCE = new DBConnection() is executed → object created10 → INSTANCE returned11
12All subsequent calls:13 → DBConnectionHelper already loaded14 → INSTANCE already initialized15 → Simply returned (no lock, no check, no overhead)Why Is It Thread-Safe Without Synchronization?
Java's class loading mechanism is inherently thread-safe. The JVM guarantees that a class's static initializers are executed exactly once, even in a multi-threaded environment. So private static final DBConnection INSTANCE = new DBConnection() is guaranteed to run only once — no synchronized needed.
Advantages
| Detail | |
|---|---|
| ✅ Lazy | Object created only when first needed |
| ✅ Thread-safe | JVM class loading is inherently thread-safe |
| ✅ Fast | No synchronization overhead after object creation |
✅ No volatile | No memory visibility issues |
| ✅ Simple | Clean, readable code |
1.8 Method 6: Enum Singleton
Concept
Javaenumtypes are singleton by design. The JVM guarantees that each enum constant is instantiated exactly once per JVM.
This is the simplest singleton implementation — and the most robust.
Implementation
1public enum DBConnection {2 INSTANCE; // This is the singleton instance3
4 // Add your connection methods here5 public void connect() {6 System.out.println("Connecting to DB...");7 }8
9 public void query(String sql) {10 System.out.println("Executing: " + sql);11 }12}How to Use It
1public class Application {2 public static void main(String[] args) {3
4 DBConnection conn1 = DBConnection.INSTANCE;5 DBConnection conn2 = DBConnection.INSTANCE;6
7 System.out.println(conn1 == conn2); // true — same object8
9 conn1.connect();10 conn1.query("SELECT * FROM users");11 }12}Why Enum Works as Singleton
Java enums come with built-in guarantees:
- Enum constructors are always
private— you cannot callnewon an enum from outside - Each enum constant is instantiated exactly once per JVM — this is guaranteed by the JVM specification
- Enum instances are created eagerly at class load time
In just two lines, enum gives you what the other approaches need 20+ lines to implement.
Enum Singleton vs. Other Methods
| Feature | Enum Singleton | Bill Pugh | DCL |
|---|---|---|---|
| Thread-safe | ✅ JVM guaranteed | ✅ Class loading | ✅ With volatile |
| Lazy | ❌ Eager | ✅ Yes | ✅ Yes |
| Serialization-safe | ✅ Yes | ❌ Needs extra code | ❌ Needs extra code |
| Reflection-safe | ✅ Yes | ❌ Can be broken | ❌ Can be broken |
| Code simplicity | ✅ 2 lines | ✅ Simple | ❌ Complex |
1.9 Singleton Methods Comparison
| Method | Lazy? | Thread-Safe? | Performance | Complexity | Recommended? |
|---|---|---|---|---|---|
| Eager Initialization | ❌ | ✅ | Fast | Low | ⚠️ Wastes memory |
| Lazy Initialization | ✅ | ❌ | Fast | Low | ❌ Not thread-safe |
| Synchronized Method | ✅ | ✅ | Very slow | Low | ❌ Performance issue |
| Double-Checked Locking | ✅ | ✅ (with volatile) | Good | High | ⚠️ Complex |
| Bill Pugh Solution | ✅ | ✅ | Excellent | Medium | ✅ Recommended |
| Enum Singleton | ❌ | ✅ | Fast | Very Low | ✅ Recommended |
2. Immutable Classes
2.1 What is an Immutable Class?
Definition
An immutable class is a class whose objects cannot be changed after they are created. Once an object is constructed and its state is set, that state remains fixed for the lifetime of the object.
You have already encountered immutability: String in Java is immutable. When you do:
1String s = "hello";2s = s + " world"; // Does NOT modify "hello" — creates a NEW String objectThe original "hello" object is never changed. A brand new "hello world" object is created.
Real-World Analogy
Think of an immutable object like a sealed, printed book. Once printed, you cannot change the words inside. If you want a different version, you must print a completely new book.
Benefits of Immutability
| Benefit | Explanation |
|---|---|
| Thread safety | Immutable objects can be shared across threads without synchronization — they cannot be corrupted |
| Simplicity | No need to track state changes; easier to reason about |
| Safe sharing | Can freely share references without defensive copying by the caller |
| Cache-friendly | Values can be cached and reused safely (e.g., String Pool) |
| Good for keys | Immutable objects make excellent HashMap keys (hash never changes) |
2.2 Rules for Creating Immutable Classes
There are five essential rules:
Rule 1: Declare the Class as `final`
1public final class ImmutablePerson {2 // ...3}Why? If the class is not final, a subclass could extend it and add mutable state or override methods, breaking immutability:
1// Without final — this is POSSIBLE and DANGEROUS:2public class MutablePerson extends ImmutablePerson {3 public void setName(String name) { this.name = name; } // breaks immutability!4}Making the class final prevents subclassing entirely.
Rule 2: Make All Fields `private` and `final`
1public final class ImmutablePerson {2 private final String name; // private: no direct external access3 private final List<String> pets; // final: reference cannot be reassigned4}private→ No external code can directly read or write the fieldfinal→ The field can only be assigned once (in the constructor); it cannot be reassigned later
Rule 3: Initialize All Fields via Constructor Only
1public final class ImmutablePerson {2 private final String name;3 private final List<String> pets;4
5 public ImmutablePerson(String name, List<String> pets) {6 this.name = name;7 this.pets = new ArrayList<>(pets); // defensive copy (explained below)8 }9}Fields are set once in the constructor and never again. This is the only moment state is assigned.
Rule 4: No Setter Methods
1// ✅ Only getters — no setters2public String getName() { return name; }3
4// ❌ NO setters allowed5// public void setName(String name) { this.name = name; } ← FORBIDDENWithout setters, there is no public API for changing the object's state.
Rule 5: Return Defensive Copies from Getters (for Mutable Fields)
This is the most subtle and commonly missed rule. It applies specifically to mutable fields like List, Map, Set, arrays, and other objects.
This is explained in full detail in the next section.
2.3 The Collection Trap Defensive Copying
The Problem
Consider this field:
1private final List<String> pets;The final keyword means: this reference (pets) will always point to the same List object. It does NOT mean the list's contents cannot change.
1pets (reference) ─────────► [List Object: "SJ", "PJ"]2 ↑3 final: cannot point to a different list object4 5 But the List object's CONTENTS can still change:6 pets.add("Kiwi") → [List Object: "SJ", "PJ", "Kiwi"] ← MUTABLE!So if your getter returns the actual list:
1// DANGEROUS getter — returns the actual internal list2public List<String> getPets() {3 return pets; // ← returning the REAL list4}An external caller can do:
1ImmutablePerson person = new ImmutablePerson("Alice", Arrays.asList("SJ", "PJ"));2
3List<String> petList = person.getPets(); // gets the REAL internal list4petList.add("Hallo"); // MUTATES the internal list!5
6System.out.println(person.getPets()); // ["SJ", "PJ", "Hallo"] ← state changed!Immutability is broken even though pets is final.
The Solution: Defensive Copy
Return a copy of the internal collection, not the collection itself:
1// SAFE getter — returns a COPY of the internal list2public List<String> getPets() {3 return new ArrayList<>(pets); // defensive copy4}Now the caller gets their own independent copy. Any changes they make affect only their copy, not the internal state:
1ImmutablePerson person = new ImmutablePerson("Alice", Arrays.asList("SJ", "PJ"));2
3List<String> petList = person.getPets(); // gets a COPY4petList.add("Hallo"); // modifies the COPY — not the original5
6System.out.println(person.getPets()); // ["SJ", "PJ"] ← UNCHANGED ✅Defensive Copy Memory Visualization
1After construction:2 person.pets ──────────────► [List: "SJ", "PJ"] ← internal list3
4After person.getPets() call:5 person.pets ──────────────► [List: "SJ", "PJ"] ← internal list (unchanged)6 returned copy ────────────► [List: "SJ", "PJ"] ← NEW independent copy7
8After caller does copy.add("Hallo"):9 person.pets ──────────────► [List: "SJ", "PJ"] ← STILL unchanged ✅10 returned copy ────────────► [List: "SJ", "PJ", "Hallo"] ← only copy is modified11 (copy has no references → eligible for GC after caller is done)Defensive Copy in Constructor Too
You must also defensively copy mutable objects in the constructor. Otherwise:
1// DANGEROUS constructor2public ImmutablePerson(String name, List<String> pets) {3 this.name = name;4 this.pets = pets; // ← storing the CALLER'S list directly5}The caller could do:
1List<String> myList = new ArrayList<>(Arrays.asList("SJ", "PJ"));2ImmutablePerson person = new ImmutablePerson("Alice", myList);3
4myList.add("Hallo"); // caller modifies their list5// person.pets is the SAME list — now contains "Hallo"! State changed!Fix — defensive copy in constructor:
1public ImmutablePerson(String name, List<String> pets) {2 this.name = name;3 this.pets = new ArrayList<>(pets); // store a COPY, not the original4}Now even if the caller modifies their original list after construction, person.pets is unaffected.
2.4 Complete Immutable Class Example
1import java.util.ArrayList;2import java.util.List;3
4// Rule 1: Class declared final5public final class ImmutablePerson {6
7 // Rule 2: All fields private and final8 private final String name;9 private final List<String> petNames;10
11 // Rule 3: Fields initialized only in constructor12 public ImmutablePerson(String name, List<String> petNames) {13 this.name = name;14 // Defensive copy in constructor — protects against caller mutation15 this.petNames = new ArrayList<>(petNames);16 }17
18 // Rule 4: Only getters — NO setters19 public String getName() {20 return name; // String is immutable — safe to return directly21 }22
23 // Rule 5: Return defensive copy for mutable fields24 public List<String> getPetNames() {25 return new ArrayList<>(petNames); // defensive copy26 }27
28 @Override29 public String toString() {30 return "ImmutablePerson{name='" + name + "', pets=" + petNames + "}";31 }32}Usage Demonstration
1import java.util.Arrays;2import java.util.List;3
4public class Main {5 public static void main(String[] args) {6
7 List<String> pets = new ArrayList<>(Arrays.asList("SJ", "PJ"));8 ImmutablePerson person = new ImmutablePerson("Alice", pets);9
10 System.out.println(person); // ImmutablePerson{name='Alice', pets=[SJ, PJ]}11
12 // Try 1: Modify the original list passed to constructor13 pets.add("Extra"); // modifying caller's original list14 System.out.println(person); // STILL: ImmutablePerson{name='Alice', pets=[SJ, PJ]} ✅15
16 // Try 2: Modify the list returned by getter17 List<String> returned = person.getPetNames();18 returned.add("Hallo"); // modifying the COPY19 System.out.println(person); // STILL: ImmutablePerson{name='Alice', pets=[SJ, PJ]} ✅20
21 // Try 3: Change the name — no setter exists22 // person.setName("Bob"); // ❌ COMPILE ERROR: no setName method23
24 // Try 4: Access field directly — private25 // person.name = "Bob"; // ❌ COMPILE ERROR: name has private access26
27 // Try 5: Subclass and override — class is final28 // class SubPerson extends ImmutablePerson { } // ❌ COMPILE ERROR: cannot extend final class29 }30}ImmutablePerson{name='Alice', pets=[SJ, PJ]}
ImmutablePerson{name='Alice', pets=[SJ, PJ]}
ImmutablePerson{name='Alice', pets=[SJ, PJ]}State never changed. ✅
Well-Known Immutable Classes in Java
| Class | Package |
|---|---|
String | java.lang |
Integer, Long, Double, etc. | java.lang |
BigDecimal, BigInteger | java.math |
LocalDate, LocalTime, LocalDateTime | java.time |
Optional | java.util |
3. Wrapper Classes
Overview
Wrapper classes
provide an object representation for each of Java's eight primitive data types.
Every primitive type has a corresponding wrapper class in java.lang:
| Primitive | Wrapper Class |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Why Do Wrapper Classes Exist?
Java's Collections Framework (e.g., ArrayList, HashMap) can only work with objects, not primitives. Wrapper classes allow primitives to be used as objects:
1// This does NOT compile — ArrayList needs objects, not primitives2// ArrayList<int> list = new ArrayList<>(); // ❌3
4// This works — Integer is an object5ArrayList<Integer> list = new ArrayList<>(); // ✅6list.add(42); // autoboxing: 42 (int) → Integer(42)Autoboxing and Unboxing
Autoboxing
is the automatic conversion of a primitive to its wrapper class by the Java compiler. Unboxing is the automatic conversion of a wrapper class back to its primitive.
1// Autoboxing — int → Integer (automatic, done by compiler)2int primitive = 42;3Integer wrapped = primitive; // compiler inserts: Integer.valueOf(42)4
5// Unboxing — Integer → int (automatic)6Integer wrapped2 = Integer.valueOf(100);7int primitive2 = wrapped2; // compiler inserts: wrapped2.intValue()Useful Methods in Wrapper Classes
1// Parsing strings to primitives2int x = Integer.parseInt("123"); // → 1233double d = Double.parseDouble("3.14"); // → 3.144
5// Converting to different bases6String binary = Integer.toBinaryString(10); // → "1010"7String hex = Integer.toHexString(255); // → "ff"8String octal = Integer.toOctalString(8); // → "10"9
10// Max and Min values11System.out.println(Integer.MAX_VALUE); // → 214748364712System.out.println(Integer.MIN_VALUE); // → -214748364813
14// Comparing15int result = Integer.compare(5, 10); // → negative (5 < 10)Integer Caching Important Gotcha
Java caches Integer objects for values between -128 and 127 (inclusive):
1Integer a = 127;2Integer b = 127;3System.out.println(a == b); // true ← same cached object4
5Integer c = 128;6Integer d = 128;7System.out.println(c == d); // false ← different objects (outside cache range)8System.out.println(c.equals(d)); // true ← same value.equals() to compare Integer values, never ==. The == operator compares object references, not values — and the Integer cache makes this unpredictable.4. Summary Diagrams
Singleton Pattern Decision Flow
Immutable Class Checklist
5. Common Mistakes
Singleton Mistakes
Mistake 1: Forgetting `volatile` in Double-Checked Locking
1// ❌ WRONG — missing volatile2private static DBConnection connObject = null;3
4// ✅ CORRECT5private static volatile DBConnection connObject = null;Without volatile, the double-checked locking pattern is broken due to CPU caching and instruction reordering.
Mistake 2: Public Constructor in Singleton
1// ❌ WRONG — public constructor breaks singleton2public class DBConnection {3 public DBConnection() { } // anyone can call new DBConnection()!4}5
6// ✅ CORRECT7public class DBConnection {8 private DBConnection() { } // only this class can instantiate9}Mistake 3: Non-Static `getInstance()` Method
1// ❌ WRONG — how would you call it without an object?2public DBConnection getInstance() { return connObject; }3
4// ✅ CORRECT5public static DBConnection getInstance() { return connObject; }Immutable Class Mistakes
Mistake 4: Missing `final` on Class
1// ❌ WRONG — subclass can break immutability2public class ImmutablePerson {3 // ...4}5
6// ✅ CORRECT7public final class ImmutablePerson {8 // ...9}Mistake 5: Returning the Actual Mutable Collection from Getter
1// ❌ WRONG — caller can modify internal list2public List<String> getPetNames() {3 return petNames; // returns actual internal list4}5
6// ✅ CORRECT — returns a defensive copy7public List<String> getPetNames() {8 return new ArrayList<>(petNames);9}Mistake 6: Not Defensively Copying in Constructor
1// ❌ WRONG — caller can modify the list after construction2public ImmutablePerson(String name, List<String> pets) {3 this.name = name;4 this.pets = pets; // storing the caller's reference5}6
7// ✅ CORRECT8public ImmutablePerson(String name, List<String> pets) {9 this.name = name;10 this.pets = new ArrayList<>(pets); // store a copy11}Mistake 7: Thinking `final` on a Collection Means Its Contents Are Immutable
1private final List<String> pets = new ArrayList<>();2
3pets = new ArrayList<>(); // ❌ COMPILE ERROR — cannot reassign a final reference4pets.add("NewPet"); // ✅ ALLOWED — final only locks the reference, not the contents!final on a collection means the reference is fixed, not the contents. You can still add(), remove(), and set() items. This is why defensive copying is essential.6. Best Practices
Singleton
- Prefer Bill Pugh or Enum for new code — they are the cleanest, safest implementations.
- Always use
volatilewith Double-Checked Locking — omitting it is a production bug. - Never make the constructor public — that would allow bypassing
getInstance(). - Be careful with serialization — if your singleton implements
Serializable, addreadResolve()to prevent deserialization from creating a second instance (or use Enum which handles this automatically). - Consider dependency injection — in modern Spring/CDI applications, the framework manages singleton beans; hand-rolling singleton is less common.
Immutable Classes
- Always declare immutable classes
final— prevents subclassing attacks. - Defensively copy mutable inputs in the constructor — protect against caller mutation after construction.
- Defensively copy mutable outputs in getters — protect internal state from external modification.
Stringis safe to return directly — it is already immutable; no defensive copy needed.- For deep immutability (nested mutable objects), recursively copy or use immutable wrappers (e.g.,
Collections.unmodifiableList()). - Prefer immutability by default — immutable objects are inherently thread-safe and easier to test.
7. Interview Notes
Commonly Asked Questions
Q1: What is a Singleton class and why is it used?
Answer: A Singleton class ensures that only one object of that class exists throughout the application's lifetime. Used for expensive shared resources like database connections, logging, configuration managers, and caches.
Q2: What are the different ways to implement a Singleton?
Answer: Eager Initialization, Lazy Initialization, Synchronized Method, Double-Checked Locking (with volatile), Bill Pugh Solution (static nested class), and Enum Singleton.
Q3: Why is `volatile` necessary in Double-Checked Locking?
Answer: Without volatile, two issues arise:
- Visibility — a thread may read a stale
nullfrom its CPU cache even after another thread has already created the object and written it to main memory. - Reordering — the JVM can reorder
connObject = new DBConnection()such that the reference is assigned before the constructor completes, causing another thread to see a partially constructed object.
volatile forces all reads/writes to go directly to main memory (bypassing cache) and prevents reordering.
Q4: Which Singleton implementation is the best?
Answer: Bill Pugh Solution (static nested class) for most cases — lazy, thread-safe, no synchronization overhead. Enum Singleton if you also need serialization safety and protection against reflection attacks.
Q5: What is the difference between Eager and Lazy Initialization?
Answer: Eager creates the object when the class is loaded (even if never used — wastes memory). Lazy creates the object only on the first call to getInstance() (memory-efficient, but not thread-safe without additional measures).
Q6: What is an Immutable class? Name some examples.
Answer: A class whose state cannot be changed after object creation. Examples: String, Integer, BigDecimal, LocalDate.
Q7: How do you create an Immutable class?
Answer: Five rules:
- Declare the class
final(no subclassing) - All fields
privateandfinal - Initialize fields only in the constructor
- No setter methods
- Return defensive copies from getters for mutable fields
Q8: Why is `String` immutable in Java?
Answer: Security (can't be modified after use), String Pool efficiency (safe sharing), thread safety, and suitability as HashMap keys (hash code never changes).
Q9: Does `final` on a List mean its contents can't change?
Answer: No. final on a collection means the reference cannot be reassigned to a different list object. The contents (elements) of the list can still be added, removed, or modified. This is why defensive copying is necessary in immutable classes.
Q10: What is autoboxing and unboxing?
Answer: Autoboxing is the automatic compiler-inserted conversion of a primitive (e.g., int) to its wrapper class (Integer). Unboxing is the reverse — wrapper class to primitive. Introduced in Java 5.
8. Practice Questions
Easy
- What is the purpose of making a constructor
privatein a Singleton class? - What does the
statickeyword mean when applied to the singleton instance field? - Name two real-world scenarios where a Singleton is appropriate.
- List the five rules for creating an immutable class.
- What is the difference between
String s = "hello"andString s = new String("hello")in terms of immutability? - What are the eight primitive types and their corresponding wrapper classes?
Medium
- Implement a thread-safe Singleton using the Synchronized Method approach. Then explain its performance drawback.
- Implement the Bill Pugh Singleton. Explain why it is lazy without using
synchronized. - Why does
finalon aListfield not guarantee immutability of the list's contents? Provide a code example demonstrating the problem and the fix. - Write a complete immutable class
Personwith aString nameandList. Demonstrate with code that its state cannot be changed from outside.hobbies - Explain the two memory issues (visibility and reordering) that make Double-Checked Locking without
volatileincorrect. - What is the difference between
==and.equals()forIntegerobjects? When does the Integer cache affect==comparisons?
Hard
- Implement all six Singleton patterns from memory. For each, state one advantage and one disadvantage.
- A colleague implements Double-Checked Locking but forgets
volatile. Write a scenario (with thread timeline) showing exactly how two objects can be created due to CPU caching. - A Singleton class implements
Serializable. What problem arises during deserialization, and how do you fix it without using Enum? - Could reflection be used to break a Singleton? Show how, and explain why Enum Singleton is immune.
- Design an immutable
ImmutableMatrixclass that wraps a 2Dint[][]array. What special considerations does a 2D array require compared to a simpleList? - Compare Enum Singleton vs. Bill Pugh Solution on: laziness, serialization safety, reflection safety, code simplicity, and thread safety.
9. Quick Revision Summary
1☕ SINGLETON, IMMUTABLE & WRAPPER — KEY POINTS2
3🔒 SINGLETON CLASS:4 Purpose: Only ONE object per application/JVM5 Use cases: DB connection, Logger, Config, Cache6
7 6 Patterns:8 1. Eager → create at class load | simple | wastes memory if unused9 2. Lazy → create on first use | simple | NOT thread-safe10 3. Synchronized → thread-safe | very slow (lock on every call)11 4. DCL → fast + thread-safe | needs volatile | complex12 5. Bill Pugh → BEST: lazy + thread-safe + no lock | static nested class13 6. Enum → SIMPLEST: JVM-guaranteed | serialization-safe14
15 DCL Template:16 private static volatile MyClass instance = null;17 public static MyClass getInstance() {18 if (instance == null) { // Check 1 (no lock)19 synchronized(MyClass.class) {20 if (instance == null) { // Check 2 (with lock)21 instance = new MyClass();22 }23 }24 }25 return instance;26 }27
28 volatile → bypasses CPU cache; reads/writes go to main memory29 → prevents instruction reordering30 → REQUIRED for correct DCL31
32🔐 IMMUTABLE CLASS:33 Purpose: Object state cannot change after construction34
35 5 Rules:36 1. Class is final (no subclassing)37 2. Fields are private + final (no external access, no reassignment)38 3. Set fields in constructor (only once)39 4. No setter methods (no way to change state)40 5. Defensive copy for mutable fields (List, Map, arrays, etc.)41
42 KEY TRAP: final List ≠ immutable list contents!43 → Always return new ArrayList<>(internalList) from getters44 → Always store new ArrayList<>(inputList) in constructor45
46 Examples: String, Integer, BigDecimal, LocalDate47
48📦 WRAPPER CLASSES:49 Primitive → Wrapper:50 int→Integer, long→Long, double→Double, char→Character,51 boolean→Boolean, byte→Byte, short→Short, float→Float52
53 Autoboxing: int → Integer (automatic by compiler)54 Unboxing: Integer → int (automatic by compiler)55
56 Integer cache: -128 to 127 cached57 → a == b may be TRUE for cached range58 → ALWAYS use .equals() to compare Integer values59
60⚠️ KEY INTERVIEW POINTS:61 • volatile is REQUIRED for correct DCL — without it, DCL is BROKEN62 • final on a collection = reference is fixed, contents still mutable63 • Bill Pugh = best general-purpose singleton64 • Enum singleton = serialization-safe, reflection-safe, simplest65 • Immutable objects are inherently thread-safe66 • Defensive copy needed both IN constructor AND IN gettersEnd of Chapter — Singleton, Immutable & Wrapper Classes
volatile keyword in depth — memory visibility, happens-before, full explanation
- Exception Handling — try-catch-finally, checked vs unchecked, custom exceptions
- Multithreading — threads, synchronization, locks, concurrency utilitiesStudy Guide generated from: Java Basics to Advanced — Classes Part 4: Singleton, Immutable & Wrapper Classes
Mastery check
How well can you recall this?
Finished this lesson?