When you use “==” (i.e. shallow comparison), you are actually comparing the two object references to see if they point to the same object. When you use “equals(…)”, which is a “deep comparison” that
compares the actual string values. For example:
The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer, thus the contents of the two String objects are identical, but they are 2 distinct objects having 2 distinct references s1 and s2. This means that s1 and s2 do not refer to the same object and are, therefore, not ==, but equals( ) as they have the same value “Hello”. The s1 == s3 is true, as they both point to the same object due to internal caching. The references s1 and s3 are interned and points to the same object in the string pool.
String Pool Caches and you create a String object as a literal without the "new" keyword for caching
Create a String object as a literal without the “new” keyword for caching
In Java 6 — all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool.
In Java 7 – the string pool was relocated to the heap. So, you are not restricted by the limited size.
compares the actual string values. For example:
public class StringEquals { public static void main(String[ ] args) { String s1 = "Hello"; String s2 = new String(s1); String s3 = "Hello"; System.out.println(s1 + " equals " + s2 + "--> " + s1.equals(s2)); //true System.out.println(s1 + " == " + s2 + " --> " + (s1 == s2)); //false System.out.println(s1 + " == " + s3+ " --> " + (s1 == s3)); //true } }
Create a String object as a literal without the “new” keyword for caching
String Pool Caches and you create a String object as a literal without the "new" keyword for caching
Create a String object as a literal without the “new” keyword for caching
In Java 6 — all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool.
In Java 7 – the string pool was relocated to the heap. So, you are not restricted by the limited size.