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 you "modify"/concatenate the
+=, 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
String myStringBuilder = new StringBuilder("Hello."); myStringBuilder.append(" "); myStringBuilder.append("My name is Kevin"); System.out.println(myStringBuilder.toString());
String concatenation is translated into
StringBuilder operations automatically by modern Java compilers.