-1

This question already has an answer here:

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";
    }
}

marked as duplicate by gnat, Jules, Kilian Foth, user53019, TZHX Feb 7 '16 at 20:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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. – Anthony Pegram Feb 2 '16 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. – Anthony Pegram Feb 2 '16 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 Feb 2 '16 at 17:21
  • 4
    @AnthonyPegram you've clearly never changed the value of 5 or 4. – user40980 Feb 2 '16 at 17:38
20

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.