Java Interview Question

Use this intermediate question and answer to prepare for your next Java interview.

Are two Strings containing identical text always equal in every way, every time?

No. If the Strings are instantiated using the String constructor, then they will have the same value but will reference distinct, and therefore different, objects.


String S1 = new String("Hello"); 
String S2 = new String("Hello");

So, writing S1 == S2 will be false when either S1, S2, or both are created using the String constructor, because they are pointing to different objects. Using S1.equals(S2) will always be true if they have the same text. The above example also results in the creation of 3 objects: 1 in the constant String pool and 2 in the main heap space.

When Strings are created using literals, Java reuses instances from the constant String pool where applicable. So, in that case, even S1 == S2 will be true.

Looking for developers?