I was learning string concepts, so wrote a code,expected a different output but got something very unexpected.
class stringmute
{
public static void main(String[] args)
{
String s1="Hello "; //string one.
System.out.println("Str1:"+s1);
String s2= s1+"world"; //New String.
System.out.println("Str2="+s2);
s1=s1+"World!!"; //This should produce only Hello right?
System.out.println("Str1 modified:"+s1);
}
}
when I execute the above code i get the output as:
Str1:Hello
Str2=Hello world
Str1 modified:Hello World!!
if i've done something wrong please let me know. Since strings are immutable, which implies we should get the output of the "Str1 Modified" as "HELLO" instead of "HELLO WORLD!!".
Quoting from Effective Java: The only real disadvantage of immutable classes is that they require a separate object for each distinct value. Creating these objects can be costly, especially if they are large.
The String is immutable, so its value cannot be changed. If the String doesn't remain immutable, any hacker can cause a security issue in the application by changing the reference value. The String is safe for multithreading because of its immutableness. Different threads can access a single “String instance”.
When you assign s1 as :
s1=s1+"World!!";
New String created in jvm string pool and assigned to s1.
So it's value became "Hello World!!"
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