I'm trying to understand exactly how Java strings are immutable. I get that this should probably be an easy concept, but after reading several online web pages I still don't quite understand.
I don't understand how Java Strings are "immutable". I currently have the following code:
public static void main(String[] args) {
String name = "Jacob Perkins";
System.out.println( name );
name = name + "!";
System.out.println( name );
}
My output is the following:
Jacob Perkins
Jacob Perkins!
Why is this happening if a string is supposed to be immutable? Why am I able to re-assign a value to the string?
The duplicate characters are found in the string using a nested for loop.
To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.
The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned.
Let an image explain this for you:
On the left side, you have the variable, which in fact is a reference.
String name = "Jacob Perkins;"
The String "Jacob Perkins" is created, and name
points to it.name = name + "!";
A new String "Jakob Perkins!" is created, and the reference now points to the new String. The old one, however, remains unchanged, because String is immutable.The string itself, once created, can never be changed. What your code sample does is to replace the string in name with a new string that was constructed from the previous contents of name, and an exclamation point. (The original contents of name, which are no longer referenced by any variable, will eventually be reaped by the garbage collector.)
If you were to examine the compiled code (or step through it with a debugger), you would discover that your name + "!"
expression had been compiled into the creation of a StringBuilder object and a few operations on that object.
That is, the strings are immutable, but the variable name is not. Its value changes, to point to different strings. The strings themselves never change.
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