When you do this, you are actually creating string literals:
String s1 = "Hello";
String s2 = "Hello";
The compiler finds identical string literals and then optimizes by keeping one instance in the heap and making all the variables in the stack point to it. So doing an ==
will return true because they point to the same memory address.
When you do this, you are creating string objects:
String s1 = new String("Hello");
String s2 = new String("Hello");
The instantiation will create unique space on the heap for each of these and the stack variables will point to those separate locations. Thus, these will be equal using .equals()
because their values are the same, but they will not be equal using ==
because they are different objects in the heap memory space.