search
HomeJavajavaTutorialImmutable Class in Java

In this article, we will explain the immutable class in java. Also, we will see the uses of immutable class. There will be java code examples showing how immutable class can be created in java. An immutable class is a class whose contents cannot be changed.

Following are some important points regarding the immutable class:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Objects of an immutable class are called immutable objects. While dealing with immutable objects, we are not allowed to change an object’s state after its creation. Whenever the state of an object is changed, we get a new object.
  • Immutable classes do not provide any methods for changing their content.
  • In Immutable classes, only getter methods are available and not setter methods.
  • Immutable classes are by default thread-safe in nature.
  • Java legacy classes, wrapper classes, String class, are examples of immutable classes in java.

How to Use an Immutable Class in Java?

Before using this class, it is important to know how an immutable class is created. Following are important points to be kept in mind while creating the class:

  • An immutable class must be final as it should not be inherited.
  • All fields of an immutable class should be made final.
  • If any mutable object is used as a field in an immutable class, then special handling has to be implemented so as to prevent its contents from being modified.
  • A public constructor should be present.
  • Getter methods for all the variables should be defined.
  • Setter methods should not be present for any variables.

Following are the main uses of immutable classes in java:

  • Simplicity: Since in the case of immutable class, each class is in a single state; therefore, it is a simple design pattern.
  • Thread Safe: Another advantage of immutable class comes in the case of a multithreaded environment where no synchronization is required because of the thread-safe nature of the immutable class.
  • Robust Design: Writing immutable classes in an application results in robust code.

Apart from the listed advantages, there can be some performance issues when using immutable classes. Hence where thread safety and other features are not important, we can consider using mutable classes for performance improvement.

Examples of Immutable Class in Java

Below are the examples mentioned:

Example #1 – Creating Immutable Class

Now we will see java code examples showing the creation of immutable classes in java. Here is a java code example showing how immutable classes are created in java:

Code:

package com.edubca.immutabledemo;
public final class ImmutableDemo {
final String studentName;
final int rollNumber;
public ImmutableDemo  (String studentName, int rollNumber) {
this.studentName = studentName;
this.rollNumber = rollNumber;
}
public String getStudentName() {
return studentName;
}
public int getRollNumber() {
return rollNumber;
}
public static void main(String[] args) {
ImmutableDemo obj = new ImmutableDemo  ("John" , 100);
// Since no getters are available contents cannot be modified.
// Also as variables are declared final they cannot be modified
System.out.println("Name is " + obj.getStudentName());
System.out.println("Roll Number is " + obj.getRollNumber());
}
}

Output:

Immutable Class in Java

The above code shows the creation of an immutable class that does not contain any mutable object as a class member.

Example #2 – Immutable Class Example in Java

Now we will see how to create immutable classes having mutable objects as their members. Some special handling is required In order to maintain immutability in this case.

Problem with a Mutable Object in an Immutable Class:

Here is code example normal showing creation of immutable class having mutable members in it:

Code:

package com.edubca.immutabledemo;
import java.util.Date;
import java.text.SimpleDateFormat;
public final class ImmutableDemo {
final String studentName;
final int rollNumber;
final Date birthDate;
public ImmutableDemo  (String studentName, int rollNumber, Date birthDate) {
this.studentName = studentName;
this.rollNumber = rollNumber;
this.birthDate=birthDate;
}
public String getStudentName() {
return studentName;
}
public int getRollNumber() {
return rollNumber;
}
public Date getBirthDate() {
return birthDate;
}
public static void main(String[] args) throws Exception {
String birthDate= "31/09/1997";
ImmutableDemo obj = new ImmutableDemo  ("John" , 100, new SimpleDateFormat("dd/MM/yyyy").parse(birthDate));
System.out.println("Name is " + obj.getStudentName());
System.out.println("Roll Number is " + obj.getRollNumber());
System.out.println("Birth date is " + obj.getBirthDate());
obj.getBirthDate().setTime(1000);
System.out.println("After changing birth date>>>>>>>>>>>>");
System.out.println("Name is " + obj.getStudentName());
System.out.println("Roll Number is " + obj.getRollNumber());
System.out.println("Birth date is " + obj.getBirthDate());
}
}

Output:

Immutable Class in Java

From the above output, we can see that the contents of the object are changed since the birth date is changed. This breaks the rules of the immutable class.

The Solution to the Problem with a Mutable Object in an Immutable Class:

In order to handle such cases, some changes need to be implemented in the code. In the modified code, when returning mutable objects from the getting method, we do not return the original object; rather, we return the clone of the object. Hence changes to cloned objects do not have any effect on the original object. Here is the modified code:

Code:

package com.edubca.immutabledemo;
import java.util.Date;
import java.text.SimpleDateFormat;
public final class ImmutableDemo {
final String studentName;
final int rollNumber;
final Date birthDate;
public ImmutableDemo  (String studentName, int rollNumber, Date birthDate) {
this.studentName = studentName;
this.rollNumber = rollNumber;
this.birthDate=birthDate;
}
public String getStudentName() {
return studentName;
}
public int getRollNumber() {
return rollNumber;
}
public Date getBirthDate() {
return (Date)birthDate.clone();
}
public static void main(String[] args) throws Exception {
String birthDate= "31/09/1997";
ImmutableDemo obj = new ImmutableDemo  ("John" , 100, new SimpleDateFormat("dd/MM/yyyy").parse(birthDate));
System.out.println("Name is " + obj.getStudentName());
System.out.println("Roll Number is " + obj.getRollNumber());
System.out.println("Birth date is " + obj.getBirthDate());
obj.getBirthDate().setTime(1000);
System.out.println("After changing birth date>>>>>>>>>>>>");
System.out.println("Name is " + obj.getStudentName());
System.out.println("Roll Number is " + obj.getRollNumber());
System.out.println("Birth date is " + obj.getBirthDate());
}
}

Output:

Immutable Class in Java

From the above output, we can see no change in date value; hence, the class’s immutability remains intact. 

Conclusion

From the above discussion, we have a clear understanding of java immutable classes. Also, we have seen the advantages of it.

The above is the detailed content of Immutable Class in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.