Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java strings inmutable but the code doesn't shows that [duplicate]

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!!".

like image 382
Aashish Kauul Avatar asked Jul 31 '18 16:07

Aashish Kauul


People also ask

What is the disadvantage of having string immutable in Java?

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.

What do immutable strings imply in Java?

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”.


1 Answers

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

like image 56
Emre Savcı Avatar answered Sep 25 '22 21:09

Emre Savcı