-1

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"; } } 
5
  • 3
    You know what is almost never worth thinking about? String immutability. It seems to confuse more people than it ever helps. Strings are no more immutable than integers, yet somehow people never seem to trip over themselves thinking about integer variables and member fields.CommentedFeb 2, 2016 at 17:05
  • 3
    If I had to summarize it to one basic thing, I'd say all you need to understand are methods on strings. They don't modify the original string, they return a new one. That's it. Everything about working with a string variable -- overwriting it, setting it, whatever -- is the same as any other variable.CommentedFeb 2, 2016 at 17:10
  • @AnthonyPegram That is only true if you learned math before CPU registers and assembly languages. I've happened to know about asm earlier, so I initially wrote code in mutable style, where, for example, uppercase procedure mutates it's argument.
    – scriptin
    CommentedFeb 2, 2016 at 17:21
  • 4
    @AnthonyPegram you've clearly never changed the value of 5 or 4.
    – user40980
    CommentedFeb 2, 2016 at 17:38

1 Answer 1

21

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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.