Shaney96 Shaney96 - 4 months ago 8
Java Question

What is happening when you "alter" a string in Java using "+="?

I understand that a String variable in Java is immutable and can therefore not be changed.

String myString = "Hello.";
myString += " ";
myString += "My name is Kevin";


Each time we "add" something to this String, we are effectively creating a new string, but this String has the same name as the string it is being concatenated with. Does this mean there are multiple references in memory with the name "myString"?

Answer

Each time you "modify"/concatenate the String with +=, you're creating a new String object and replacing the reference named myString with the newly-created String. So no, there is only one reference in memory, but the object the reference points to changes each time. The string is immutable, so the object cannot be modified "in place".

String is an immutable class in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified. There are many advantages of immutable classes.

There is a great answer on the Programmer's StackExchange explaining why Strings are immutable in Java, and more details about how exactly this works.

The best way to do this is to just use the StringBuilder() class:

String myStringBuilder = new StringBuilder("Hello.");
myStringBuilder.append(" ");
myStringBuilder.append("My name is Kevin");

System.out.println(myStringBuilder.toString());

However, String concatenation is translated into StringBuilder operations automatically by modern Java compilers.

Comments