Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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"?

like image 987
Shaney96 Avatar asked Aug 26 '26 11:08

Shaney96


2 Answers

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.

like image 96
Will Avatar answered Aug 29 '26 02:08

Will


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

like image 41
Mehdi Hamzezadeh Avatar answered Aug 29 '26 02:08

Mehdi Hamzezadeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!