What does the following code fragment print String string1
What does the following code fragment print?
String string1 = \"hello\";
String string2 = string1;
string1 = \"world\";
StdOut.println(string1);
StdOut.println(string2);
Solution
Please follow the code and comments for description :
CODE :
String string1 = \"hello\";
String string2 = string1;
string1 = \"world\";
StdOut.println(string1);
StdOut.println(string2);
OUTPUT :
world
hello
DESCRIPTION :
Here when check into the lines of code initially the string1 varaible has been initialised with the data as hello and the same data is been assigned to the variable string2. Later the data in the string1 is overrriden (as string is an immuatable) with the value world. So the data in the varaibles are world and hello respectively. The same is logged to the console.
Hope this is helpful.
