String s = "Hi Hello Hola";
String[] d = s.split(" ");
System.out.println(d[0] == "Hi"); // prints false
String[] e = { "Hi", "Hello", "Hola" };
System.out.println(e[0] == "Hi"); // prints true
Here we have an array d
with the values Hi
, Hello
, and Hola
. We have another array e with the same set of values.
But why does this comparison behaves differently? Why does it print false and then true?
I expected false for both! As we are comparing a string literal value with the string value by using ==
.
Why is this difference?
Update Here my question is not about the comparison of String values. I'm aware of the differences between ==
which compares the references and equals()
which compares the content of the string.
From the answers, i understand that in the second case, Hi
value is interned and refers to the same object. But in the other case, split creates new values without checking the literal pool. Is it right? Am i missing anything?