DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • Genkit Flows on Kubernetes, Routed by a Decision Model: senro + jev in Go
  • AI-Powered CI Test Failure Triage
  • Building a Windows App for a Resilient SSH SOCKS Proxy and Selective Browser Routing
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Java Immutable Objects

Java Immutable Objects

Want to learn more about immutable objects in Java?

By 
Yogen Rai
·
Mar. 29, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
47.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

An object is considered immutable if its state cannot change after it is constructed. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state, making them useful in concurrent applications.

For example, String objects in Java are immutables.

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class ImmutableTest {
    @Test
    public void testImmutableObjs() {
        String firstName = "yogen";
        String lastName = "rai";

        // concatenate two strings
        String fullName = firstName.concat(" ").concat(lastName);

        assertEquals("yogen", firstName);
        assertEquals("rai", lastName);
        assertEquals("yogen rai", fullName);
    }
}


The concatenation of firstName on " " (whitespace) and lastName is not going to modify either of them, rather create a new object which will be referenced by fullName.

String- Immutables

Figure: Strings are immutables

Defining Custom Immutable Objects

The following rules define a simple strategy for creating immutable objects:

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
  2. Make all fields final and private.
  3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

Defining Custom Immutable Object With the Date Object

Date object in java.util.* is not thread-immutable.

It is good news that new java.time.* API after JDK 8 has Date objects as immutable objects. For example, the Student object, in the example below, is immutable even if the property dateJoined is Date object.

import java.time.LocalDate;

final class Student {
    private final String name;
    private final int age;
    private final LocalDate dateJoined;

    public Student(String name, int age, LocalDate dateJoined) {
        this.name = name;
        this.age = age;
        this.dateJoined = dateJoined;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public LocalDate getDateJoined() {
        return dateJoined;
    }
}

public class TestImmutable {
    @Test
    public void testImmutableObject() {
        Student original = new Student("Yogen", 23, LocalDate.of(2016, 5, 1));

        LocalDate modifiedLocalDate = original.getDateJoined().plusYears(2);

        Student expected = new Student("Yogen", 23, LocalDate.of(2016, 5, 1));
        assertEquals(expected, original);
    }
}


The code from the above example is available on GitHub.

Benefits of Immutable Objects

  • Immutable objects are simpler to construct, test, and use as they are side-effect free.
  • They are much easier to cache since the modification on the object is not going affect it's original state.
  • Truly immutable objects are always thread-safe
  • Identity mutability problem is avoided
  • They help to avoid temporal coupling
Object (computer science) Java (programming language)

Published at DZone with permission of Yogen Rai. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook