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.
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18324)
- How to add BASIC Authentication into HttpURLConnection?(16083)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13991)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10445)