Pergunta

If Strings are immutable in Java, why is the output of this code 2GB, instead of 1GB?

class Laptop {
   String memory = "1GB";
}

class Workshop {
    public static void main(String args[]) {
       Laptop life = new Laptop();
       repair(life);
       System.out.println(life.memory);
    }

    public static void repair(Laptop laptop) {
        laptop.memory = "2GB";
    }
}
Foi útil?

Solução

You're confusing immutability of reference to object and immutability of the object itself. They are separate things.

laptop.memory is just a reference (pointer) to the object. This can be modified, i.e. you can change the reference to point to a different object - which is exactly what you did - you created a second String object containing "2GB" and assigned its reference (pointer) to the laptop.memory. Original String object is still unmodified (or maybe it's garbage collected).

Same behavior applies to all objects in Java, but primitives are different (they don't have references and are really modified directly).

BTW, you can have immutable reference in Java with final keyword:

class Laptop {
   final String memory = "1GB";
}

With this modification, your code would not compile because you attempt to modify the reference.

Licenciado em: CC-BY-SA com atribuição
scroll top