0

Consider the following case:

String cat = "cat";
String cat2 = "cat";        
out.println(cat == cat2);  // true // Uses String#equals(...)
out.println(((Object) cat) == ((Object) cat2));  // true. Object#equals(...)???
// So it should be false!

The == defaults to the .equals of the Object being compared by answer in StackOverflow.

Since, I am casting these as Objects, shouldn't they use default comparison which is reference comparison?

Community
  • 1
  • 1
Mathew Kurian
  • 5,949
  • 5
  • 46
  • 73

4 Answers4

5

Yes and that's what it is doing.

The thing with String literals is that they are the same object! To elaborate: when you are creating Strings like you are doing (which is called string literals):

String cat = "cat";
String cat2 = "cat"; 

JVM uses the so called string pool. It keeps strings in it and reuses them whenever it finds in code a literal that already is in the pool. So both cat and cat2 are referencing the same object from the string pool.

On the other hand if you'd do:

String cat = new String("cat");
String cat2 = new String("cat"); 

Then cat and cat2 would reference different objects because new creates a new String object every time and does not reuse the objects from the string pool --> the result would be as you thought it is supposed to be.

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
1

In java, compile time String constants are interned, so they are the same object! That is, cat and cat2 hold the same reference.

Unlike C++, java does not overload operators, so the == operator always compares references, like the implementation of the equals() method of the Object class.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

If two variable reference the same String literal, the JVM will automatically force the variables to reference the same String literal. This is possible becuase Strings are immutable. This also saves memory.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

There are two errors here: == doesn't "default to .equals," it always means reference comparisons, and it wouldn't matter if you were using .equals: casting an object doesn't make a difference as to which overriden version of a method gets used.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413