-2

I have this book about Java and it is telling me if I use relational operators for objects such as strings it will turn out as false. Even if two strings have the same literal value. I tested this, yet true was printed. Could someone explain why this is?

String y = "Not null";
String x = "Not null";

            if(x == y)
                System.out.println("True");
user3525476
  • 57
  • 1
  • 1
  • 4

2 Answers2

2

Both Strings are interned in the String pool so x and y refer to the same Object. The expression would not evaluate to true if you did.

String y = "Not null";
String x = new String("Not null");

Since Strings are immutable many methods typically return new String Objects. This is why its recommended to compare content using the .equals method.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

The strings are interned in the string pool and it will return the reference of the string object that is already interned in string pool(since they are equal).That is why in your case, it is evaluated to "true".

UVM
  • 9,776
  • 6
  • 41
  • 66