How do I compare strings in java?
== tests for reference equality.
.equals () for value equality.
I saw this post How do I compare strings in Java? ... And I still don't understand why you are wrong when you compare
// ... but it's 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);
Is this because they have a different name or what is the reason?
-1
source to share
2 answers
This is because the == operator is comparing memory addresses, not content.
Please note that String is an object, not a primitive. This is probably why people are confused, you can compare primitives with the == symbol and everything will be fine, but with the objects you want to compare with their content.
+1
source to share