I have the following code:
Circle c1 = new Circle();
Circle c2 = new Circle();
System.out.println(c1 == c2);
Which outputs False
, as expected. This is because c1
and c2
are reference types and "==" checks if they refer to the same type (which they don't).
However, I recently tried this:
String a = "hello";
String b = "hello";
System.out.println(a == b);
Which for some reason outputs True
. Why is this? String is a reference type and a
and b
refer to different memory locations. I was always taught that you need to use .equals()
for this to work, which this does not!
See: https://ideone.com/CyjE49
UPDATE
THIS IS NOT A DUPLICATE!
I know the proper way to compare strings is using .eqauls()
UPDATE 2 This question may have an answer in: How do I compare strings in Java?, but the question there wasn't asking what I am asking and the answer just went in more detail than required.
Therefore searching with my same question (on Google or otherwise) means users won't be sent to that question or may dismiss it entirely due to the title of the question. Therefore it may be a good idea to keep this up for benefit of other users!