Computer Science Canada

immutable object string

Author:  hamid1455 [ Wed Nov 16, 2016 3:47 pm ]
Post subject:  immutable object string

If a String Object is immutable in Java, it means that once it is created it can not be changed right?

So if I have made a String like this:

String name = "Bob";

and I do this on the next line:

name = "Joe";

Does the second line create a new String Object and set its contents to the object name? Because I read that when you concatenate Strings, it actually creates a new String and returns that, because it can't change the original String.

Author:  Insectoid [ Wed Nov 16, 2016 6:27 pm ]
Post subject:  RE:immutable object string

I believe you are correct. name is a reference (or a pointer? I forget) to the actual object. The = operator assigns values to primitives only- Strings are objects. In this case, the primitives are pointer (or reference, I dunno, I'm a C guy) and a memory address. You are assigning the value of the String reference (or pointer) to the address of the String object you just created. This is the same reason you cannot use the == comparison operator with Strings- == will compare the addresses, not the actual content of the string.

Note that the first string is technically orphaned. Java will take care of this automatically, but other languages might not.

Author:  DemonWasp [ Wed Nov 16, 2016 8:18 pm ]
Post subject:  RE:immutable object string

Java's "references" aren't exactly like a C++ pointer or a C++ reference. They're nullable (unlike C++ references), but you can't do arithmetic on them or dereference arbitrary ones (unlike C++ pointers). If you dereference a null whatever-they-are, you get a NullPointerException so I guess we can call them pointers.

To illustrate memory for a moment:

String name = "Bob";

    name ---> "Bob"   <- A new String was created with value "Bob". The name value points to it.

name = "Joe";
              "Bob"   <- Because nothing points to this, it is "orphaned".
                         Some languages, like Java, have a Garbage Collector (GC)
                         that will pick up after you. In other languages, like C,
                         you have to pick up after yourself using delete() or free().
    name ---> "Joe"   <- This object is "live" and in use. It won't be garbage-collected,
                         and MUST NOT be delete()'d or free()'d.

name = null;
              "Bob"   <- The "Bob" string is already garbage, but hasn't been picked up yet.
                         You don't usually get to control the garbage collector; it runs when it wants.
              "Joe"   <- The "Joe" string is now garbage.

    name ---X         <- name doesn't point to anything. It doesn't keep anything "live".