next up previous
Next: Mutable objects: the class Up: Unit 02 Previous: References to objects

Immutable objects

Objects of type String are immutable objects because they have no way (no methods) to change their state, i.e., the string they represent.

Objects that cannot change their state are called immutable. They represent exactly the same information for all their lifetime.

Example:

public class UpperLowerCase {
  public static void main(String[] args) {
    String s, upper, lower;
    s = new String("Hello");
    upper = s.toUpperCase();
    lower = s.toLowerCase();
    System.out.println(s);
    System.out.print("upper = ");
    System.out.println(upper);
    System.out.print("lower = ");
    System.out.println(lower);
  }
}

Notice that this program constructs 3 different strings (that are not modified anymore):


next up previous
Next: Mutable objects: the class Up: Unit 02 Previous: References to objects