Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsObject-Oriented Programming
✓ FreeBeginner· 8 min read

Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions

Constructors and overloading, private constructors, anonymous classes, the Singleton pattern and making it thread-safe, and how to build a truly immutable class.

Published September 25, 2026


How to use this lesson

The singleton and immutable-class questions are favourites because they have a "textbook" answer and a correct answer. Most candidates give the textbook one: a lazy singleton that isn't thread-safe, or an immutable class that still leaks a mutable List. Give the correct one.

Q1. What is a constructor in Java?

Short answer: A constructor is a special block that initialises a new object. It has the same name as the class, no return type (not even void), and runs automatically when you use new.

public class Order {
    private final String id;
    private final Instant createdAt;

    public Order(String id) {                 // constructor
        this.id = Objects.requireNonNull(id);
        this.createdAt = Instant.now();
    }
}

Key points to cover:

  • If you declare no constructor, the compiler adds a default no-argument constructor. As soon as you declare any constructor, that default is no longer generated.
  • Constructors aren't methods in the strict sense. They aren't inherited and can't be static, final or abstract.
  • Use constructors to establish invariants. An object should be valid from the moment it exists.

Learn it in depth → Classes and Objects

Q2. Can a constructor be overloaded?

Short answer: Yes. A class can have several constructors with different parameter lists, and they can call each other with this(...). This is called constructor chaining, and it keeps the initialisation logic in one place.

public Order(String id)                  { this(id, Instant.now()); }
public Order(String id, Instant created) { this.id = id; this.createdAt = created; }

Key points to cover:

  • When there are many optional parameters, prefer the Builder pattern or static factory methods over a pile of overloaded constructors (the "telescoping constructor" anti-pattern).

Q3. Can a constructor be private? Why would you do that?

Short answer: Yes. A private constructor stops other classes from calling new. The typical uses are:

  • Singletons.
  • Utility classes with only static methods (such as Collections and Math).
  • Static factory methods, which control how instances are created (List.of, Optional.of).
  • Builders, where the builder calls the private constructor.
public final class StringUtils {
    private StringUtils() { throw new AssertionError("no instances"); }
    public static boolean isBlank(String s) { return s == null || s.isBlank(); }
}

Q4. What are anonymous classes, and what are their advantages?

Short answer: An anonymous class is a class without a name that is declared and instantiated in a single expression. It's typically used to implement an interface or extend a class for one-off use.

Comparator<String> byLength = new Comparator<>() {        // anonymous class
    @Override public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); }
};
Comparator<String> byLength2 = Comparator.comparingInt(String::length);   // the modern equivalent

Key points to cover:

  • Advantages:
    • Less boilerplate for single-use implementations.
    • The behaviour stays next to where it's used.
    • It can capture effectively final local variables.
  • Since Java 8, lambdas replace anonymous classes for functional interfaces. Anonymous classes are still needed when you must implement several methods, extend a class, or keep state in fields.
  • An anonymous class created in an instance method holds a hidden reference to the enclosing object, which is a possible memory-leak source. Also, this inside it refers to the anonymous object, whereas this inside a lambda refers to the enclosing object.

Q5. What is a Singleton class?

Short answer: A class that allows exactly one instance in the application (strictly, per class loader), and provides a global access point to it. Examples include a configuration registry, a metrics registry, or an in-memory cache.

Key points to cover:

  • In Spring applications you rarely write singletons by hand. Spring beans are singleton-scoped by default: one instance per container, managed and injectable. That's far easier to test than a static getInstance().

Learn it in depth → Singleton Pattern

Q6. How do you create a Singleton class?

Short answer:

  1. Make the constructor private.
  2. Hold the single instance in a private static field.
  3. Expose it through a public static accessor.

The simplest correct versions are eager initialisation, or an enum:

// 1) Eager: created when the class is initialised; thread-safe thanks to class-loading guarantees
public final class AppConfig {
    private static final AppConfig INSTANCE = new AppConfig();
    private AppConfig() { }
    public static AppConfig getInstance() { return INSTANCE; }
}

// 2) Enum: also safe against reflection and serialization attacks (recommended in Effective Java)
public enum MetricsRegistry {
    INSTANCE;
    public void increment(String name) { /* … */ }
}

Learn it in depth → Singleton Pattern

Q7. Is a singleton thread-safe?

Short answer: It depends on how it's created. A lazy singleton written like this is not thread-safe, because two threads can both see null and each create an instance:

public static Cache getInstance() {
    if (instance == null) instance = new Cache();   // race condition
    return instance;
}

Thread-safe options:

  • Eager initialisation, or an enum, as in the previous answer.
  • The holder idiom: lazy and lock-free.
  • Double-checked locking, with a volatile field.
  • A synchronized accessor: simple, but every call takes the lock.
public final class Cache {
    private Cache() { }
    private static class Holder { static final Cache INSTANCE = new Cache(); }   // loaded on first use
    public static Cache getInstance() { return Holder.INSTANCE; }
}

Key points to cover:

  • Double-checked locking needs volatile. Without it, another thread can see a reference to a partly constructed object.
  • Creating the instance safely doesn't make its state thread-safe. The singleton's own methods still need proper synchronisation if they change shared data.

Q8. What does immutability mean in Java?

Short answer: An immutable object's state can't change after construction. Any "modification" returns a new object instead. Examples: String, Integer, LocalDate, BigDecimal, and records with immutable fields.

LocalDate d = LocalDate.of(2026, 1, 31);
d.plusDays(1);                 // returns a NEW date; d is unchanged
d = d.plusDays(1);             // you must use the returned value

Q9. Why are immutable objects useful in concurrent programming?

Short answer: Their state never changes, so any number of threads can read them at the same time with no locking and no risk of seeing a half-updated object. They're thread-safe by construction.

Key points to cover:

  • With final fields, the Java Memory Model guarantees that other threads see the fully constructed values once the object is published, provided this doesn't escape during construction.
  • They also make safe HashMap keys (the hash never changes), are easy to cache and share, and are simple to reason about.

Learn it in depth → Volatile and the Java Memory Model

Q10. What are immutable classes?

Short answer: Classes whose instances can't be modified after creation. All state is set once, usually in the constructor. There are no setters, and no method leaks a way to change the internals.

Q11. How do you create an immutable class?

Short answer:

  1. Declare the class final, so no subclass can add mutability.
  2. Make all fields private final.
  3. Don't provide setters.
  4. Initialise every field in the constructor.
  5. Make defensive copies of mutable inputs and outputs, such as lists, dates and arrays.
public final class Invoice {
    private final String number;
    private final List<String> lineItems;

    public Invoice(String number, List<String> lineItems) {
        this.number = number;
        this.lineItems = List.copyOf(lineItems);     // copy in: the caller's list can't change us later
    }
    public String number() { return number; }
    public List<String> lineItems() { return lineItems; }   // List.copyOf is already unmodifiable
}

Common trap: stopping after rule 4. final List<String> items only stops the reference from changing. The list itself can still be modified through the caller's reference, or through a getter that returns it. Rule 5 is the one interviewers look for.

Key points to cover:

  • Records (Java 16+) give you final fields, a constructor and accessors automatically. Add List.copyOf in a compact constructor to finish the job:
public record Invoice(String number, List<String> lineItems) {
    public Invoice { lineItems = List.copyOf(lineItems); }
}

Learn it in depth → Records

Follow-up questions this topic invites — and their answers

Q: Can a singleton be broken? A: Yes, in three ways:

  • Reflection, by making the private constructor accessible. Guard against it by throwing an exception if an instance already exists.
  • Serialization, where deserializing creates a new instance. Guard against it by implementing readResolve() to return INSTANCE.
  • Cloning. Don't implement Cloneable.

An enum singleton is immune to all three.

Q: Is a singleton unique across the whole JVM? A: Only per class loader. App servers and plugin systems that load the same class through two class loaders get two "singletons".

Q: What's the difference between an immutable object and a final variable? A: A final variable can't be reassigned to point at another object, but the object it points to can still change (final List → add() works). Immutability is a property of the object.

Q: Why is String immutable? A: So that strings can be safely shared in the string pool, cache their hash codes, be used as secure keys (file paths, class names, URLs) without being altered after validation, and be shared between threads freely.

Previous

Abstraction, Interfaces & Encapsulation — Interview Questions

Next

Design Patterns & SOLID Basics — Interview Questions

AI Tutor

Lesson: Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.