Monday 26 December 2016

java strings inmutable but the code doesn't shows that




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



Answer



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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...