Immutable means unchangeable. In Java, when an object is defined as being immutable it means that once it has been initialized its state cannot be changed.
Primitive data types (i.e., int, short, long, byte, char, float, double, boolean) can be made immutable by using the "final" keyword. Once they have been assigned a value it cannot be changed.
Basically String class is an immutable class.StringBuffer is an mutable class.Follwing e.g. will explain it in details.
String changeString = "hello ";
changeString = changeString + "world";
System.out.println(changeString);
The output as expected is:
hello world
You might think the program is simply changing the state of the String object to append "world" but it's not that simple. As Strings are immutable and cannot have their values changed, what happens is a new String object is created with a state of "hello world" and assigned to the changeString variable.
Can u give an example class definition for an Immutable class??
ReplyDelete