Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - String immutability and Array mutability

I know that array a and b are pointing to the same place where as Strings s1, s2 are not. Why?

Code:

    String[] a = {"a","b","c"};
    String[] b = a;
    a[0] = "Z";
    String s1 = "hello";
    String s2 = s1;
    s1 = "world";
    System.out.println(Arrays.toString(a) + " - a"); //a and b are same
    System.out.println(Arrays.toString(b) + " - b");
    System.out.println(s1 + " "+ s2); // s1 and s2 are not same.

Output:

    [Z, b, c] - a
    [Z, b, c] - b
    world hello
like image 546
Charan Avatar asked Dec 24 '22 14:12

Charan


1 Answers

At point (2), s1 and s2 are pointing to the same literal in the pool. But when you change s1, another literal is created and the strings are not pointing to the same place anymore.

String s1 = "hello";
String s2 = s1; (2)
s1 = "world";

You can validate this by printing the result of

s1 == s2

Note that I didn't use equals because I'm interested in comparing references. Now as soon as you assign s1 with a different value, things will look like:

+-------+
| world |  <- s1
+-------+

+-------+
| hello |  <- s2
+-------+
like image 91
Maroun Avatar answered Jan 08 '23 18:01

Maroun