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 has the same name as the string it is being concatenated with. Does this mean there are multiple references in memory with the variable "myString"?
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.
No , you can not access to previous reference and it's left for garbage collector to collect it. in other words there is only one reference in memory which holds the current value of variable("My Name is Kevin)
note that if you r gonna change a String variable a lot , you should use StringBuilder class.
here is link to Documentation of StringBuilder class you also can find lots example for using this class on internet
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
also here is detailed answer of your question
When will a string be garbage collected in java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With