Skip to main content

Immutable class

 Creating an immutable class in Java is a common design pattern that ensures that once an object is created, its state cannot be changed. Immutable classes are useful when you want to ensure that the object’s data cannot be modified after creation, improving safety and predictability.

Steps to Create an Immutable Class in Java

  1. Make the class final to prevent subclassing, which can alter its immutability.
  2. Make all fields private and final to ensure they cannot be modified directly.
  3. Provide a constructor to initialize all fields. Ensure the constructor initializes the fields in such a way that they can't be modified after creation.
  4. Avoid setter methods to prevent modification of the fields.
  5. Ensure deep copying for mutable objects (like arrays or collections) to prevent external modification of internal data.
code here



  1. final class: The class is marked as final to prevent inheritance, ensuring that subclasses cannot change the immutability.

  2. private final fields: The fields name and age are marked as private to prevent direct access and as final to ensure they can only be assigned once.

  3. Constructor: The constructor initializes the fields. Once a Person object is created, its state (the name and age) cannot be modified.

  4. No setters: There are no setter methods for the fields, preventing modification of the object's state after it is constructed.

  5. Getter methods:The getter methods allow access to the field values but do not allow modification.

  6. Unmodifiable List:
    In this case, we use Collections.unmodifiableList(list) to ensure that the list cannot be modified by external code. The list returned by the getter method cannot be changed because it is unmodifiable.

  7. Deep Copying:
    If the mutable field is an object (e.g., Date, custom classes), ensure you create a copy of the object rather than directly storing a reference to it. This prevents external modifications.

Benefits of Immutable Classes

  • Thread Safety: Immutable objects are inherently thread-safe because their state cannot change.
  • Caching and Hashing: Since the object state is constant, they are safe to use as keys in hash-based collections (like HashMap).
  • Predictability: With immutable objects, you can rely on the fact that their state will never change after they are created.

Comments

Popular posts from this blog

Interview questions - Strings

1. Why Strings are immutable?  In Java, String is immutable , meaning once a String object is created, its value cannot be changed . Any operation that seems to modify a String actually creates a new object instead of modifying the existing one. Lets understand with below program.  find code here The String Constant Pool (also known as the String Intern Pool ) is a special memory area inside the heap where Java stores string literals to optimize memory usage and improve performance. When we create String password = "password@123"; using literal it will create instance in String constant pool and when we assign password = "changepassword", it will not change previous instance, but create new one inside String constant pool. Check hash code before and after changing value both are different. Lets understand scenario2 : code public class StringMemoryCheck {     public static void main(String[] args) {         String s1 = "Java";  // String...

Coding - Mostly Asked Coding Interview Question

 1. Print Mostly occurred string in Hello String import java.util.Map ; import java.util.Optional ; import java.util.stream.Collectors ; public class MostOccuringCharacter { // print most occuring character in hello string and write program to use optional public static void main ( String [] args ) { String str = "Hello" ; Optional < Map . Entry < Character , Long >> character = str .chars() .mapToObj( x -> ( char ) x ) .collect( Collectors . groupingBy ( x -> x , Collectors . counting ())) .entrySet() .stream() .max( Map . Entry . comparingByValue ()); if ( character .isPresent()){ System . out .println( "Most occurring character: " + character .get().getKey()); } //or character .ifPresent( c -> System . out .println( "Most occurring character: " + c .getKey())); } }

Internal Working of HashMap in Java

  A HashMap is a part of Java's Collections Framework , and it stores data in key-value pairs. Internally, it uses a hash table to store entries, making it efficient for fast lookups, insertions, and deletions. The underlying structure of a HashMap is based on a dynamic array of buckets (or "bins") and the hashing technique for quick access. Here’s an overview of how HashMap works internally: 1. Structure of HashMap A HashMap consists of the following key components: Buckets : A bucket is essentially an index in an array where hash collisions are stored. A HashMap is backed by an array, and each entry (a key-value pair) is stored in one of the array's indices (buckets). Entries (Key-Value Pairs) : Each entry is a key-value pair, stored in the buckets. Hashing : A hash function is used to determine the index (bucket) where a key-value pair will be stored. 2. Hashing Process When a key-value pair is added to a HashMap , the key undergoes a hashing process to de...