-1

== tests for reference equality.

.equals() tests for value equality.

I saw this post How do I compare strings in Java? . And I still don't get why you get false when you compare

// ... but they are not the same object new String("test") == "test" // --> false

or

String str1 = new String("JAVA");
String str2 = new String("JAVA");
System.out.println(str1==str2);

Does this happen because they have different name or what is the reason ?

Community
  • 1
  • 1
iDaniel19
  • 75
  • 7
  • 5
    [whats the difference between `equals` and `==`](http://stackoverflow.com/questions/1643067/whats-the-difference-between-equals-and), [Difference between string object and string literal](http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal) – Pshemo Nov 10 '14 at 23:02
  • `==` compares the memory (pointer) location of the objects where as `equals` is used to compare the quality of the physical contents of the object, so the two objects could have different memory locations, but are equal (based on the contract of their `equals`) – MadProgrammer Nov 10 '14 at 23:07

2 Answers2

1

That happens because the == operator compares memory addresses, not contents.

Note that String is an object, not a primitive, that is probably why people get confused, you can compare primitives with == and it will be fine, but with objects you want to compare their contents.

Juan Antonio Gomez Moriano
  • 13,103
  • 10
  • 47
  • 65
-2

Use equals. str1.equals(str2);