Tuesday 13 November 2018

Alias in Strings and Arrays in java




I am confused with a comparison between aliases in Strings and aliases in Arrays.



String a = "hello";
String b = "hello";

a == b;
>>> true

int [] a = {1,2,3};
int [] b = {1,2,3};
a == b
>>> false


I knew in Strings, when you call new String method, it would direct to a different address. Otherwise, it would take the previous address with the same String literal.

However, things do not work for arrays. Can someone explain why it gives false?


Answer



As Strings are immutable, Java can perform an optimization: when it detects that the two Strings are both initialized to refer to the same value: it only needs to make a single object of that value, and can have both String variables refer to it.



As arrays are mutable, if it were attempt to make the same optimization, a change to a (e.g. a[1]=7) would cause b to change too. This behavior isn't what one would expect, so it is not done. If you explicitly wanted that behavior, you would have explicitly set b to refer to what a referenced (e.g. int[] b = a).


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...