FAQ

Java

JSP

Servlet


Advertisement



What are mutable objects and immutable objects?

An Immutable object is a kind of object whose state cannot be modified after it is created. This is as opposed to a mutable object, which can be modified after it is created.

In Java, objects are referred by references. If an object is known to be immutable, the object reference can be shared. For example, Boolean, Byte, Character, Double, Float, Integer, Long, Short, and String are immutable classes in Java, but the class StringBuffer is a mutable object in addition to the immutable String.

class Program {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str);
str.toLower();
System.out.println(str);
}
}

The output result is

HELLO
HELLO

From the above example, the toLower() method does not impact on the original content in str. What happens is that a new String object "hello" is constructed. The toLower() method returns the new constructed String object's reference. Let's modify the above code:

class Program {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str);
String str1 = str.toLower();
System.out.println(str1);
}
}

The output result is

HELLO
hello

The str1 references a new String object that contains "hello". The String object's method never affects the data the String object contains, excluding the constructor.

In Effective Java, Joshua Bloch makes this recommendation: "Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, you should still limit its mutability as much as possible."

What are the guidelines to implement immutable object? Please visit Immutable Object.


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |