• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to Create an Immutable Class in Java

April 10, 2014 by javainterviewpoint 3 Comments

Immutable class is the one whose state cannot be changed after it is created. The best example for this is String,Integer class in Java, once instantiated the value never be changed. In this article, lets learn How to Create an Immutable Class in Java.

Immutable class has lots of advantages such as they can be used for the caching purposes as you don’t need to worry about the value changes. Immutable class is thread-safe and hence you don’t need to worry about synchronization issues and can be easily used in the multi-threaded environment.

How to Create an Immutable Class in Java?

You can make the class immutable easily by following the below pointers

*Don’t provide “setter” methods or methods that modify fields or objects referred to by fields.

As the setter method will allow you to change the state of the object and hence avoid it.

 * Make all fields final and private.

Making the fields private will let you access the fields only within the class and final keyword will let you prevent the value being changed at any cost. This increases your immutability feature.

 * Prevent overriding

The best way to prevent overriding is declaring your class as a final class.

* Factory method instance creation and Private Constructor

Use factory based instance creation, have a public method to get the object instances. Private Constructor will never allow object creation for your class

 * Never pass the reference of the Mutable objects

Immutable object like String,Integer can be passed directly whereas never pass the direct reference of the mutable object, instead create a copy and pass it

Lets take,  Date class in java which is  mutable even though you mark it with final keyword 

final Date date = new Date();  
date.setYear(2014); // This lets the value to be changed.

So in order to make it immutable we will return the copy not the direct reference of the mutable object

Date(date1.getTime());

Here date1 is a mutable object and its reference is not passed directly.

Let put all these and create the immutable class.

import java.util.Date;

public final class ImmutableClassExample 
{
   //Both String and Integer is Immutable 
   private final String val1;
   private final Integer val2;

   //Date is a Mutable field
   private final Date date1;

   public ImmutableClassExample(String val1,Integer val2,Date date1)
   {
	this.val1=val1;
	this.val2=val2;
	this.date1=new Date(date1.getTime());
   }
   public String getVal1() 
   {
 	return val1;
   }

   public Integer getVal2() 
   {
	return val2;
   }
   public Date getDate() 
   {
	return new Date(date1.getTime());
   }

   public static ImmutableClassExample getImmutableClassExampleObject(String a,Integer b,Date c)
   {
	return new ImmutableClassExample(a,b,c);
   }

   public String toString()
  {
	return val1+" --- "+val2+" --- "+date1;
  }
}

Testing our immutable class

import java.util.Date;

public class ImmutableTestMain 
{
  public static void main(String[] args) 
  {
        ImmutableClassExample ic =ImmutableClassExample.getImmutableClassExampleObject("Java",1,new Date());
	System.out.println(ic);
	ImmutableTestMain.changeValues(ic.getVal1(),ic.getVal2(),ic.getDate());
	System.out.println(ic);
   }
   public static void changeValues(String val1,Integer val2,Date d)
   {
	val1="interview";
	val2=100;
	d.setDate(10);
   }
}

You will get the output as

Java --- 1 --- Thu Apr 10 15:43:25 IST 2014
Java --- 1 --- Thu Apr 10 15:43:25 IST 2014

Hence we are sure that the class which we have created is a immutable class. 🙂 Let me know if you have any different thoughts !!

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • What is a Class in Java with Example
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • Serialization and Deserialization in Java
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example

Filed Under: Core Java, Java, Java Interview Tagged With: Immutable, Immutable Class in java, Immutable in Java, Java, Private Constructor

Comments

  1. Nissi says

    April 10, 2018 at 6:44 pm

    Simply Super Bro!!! Thank you very much.

    Reply
  2. Tim says

    September 9, 2019 at 3:28 pm

    why you made public constructor?

    Reply
    • javainterviewpoint says

      September 12, 2019 at 9:15 pm

      A public constructor is needed in order to initialize the variables

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·