java operator == uses [duplicate]
Possible Duplicates:
Strings in Java : equals vs == Comparing s开发者_C百科trings in java
is == can be apply to Strings ?
if so then what is the use of it for String's data type?
in other words although we should use equal method for comparing two string java, what is the use of == operator for String in java?
== will not compare the value of the String but its addresse. If you want to compare the value use the method equals().
When you want to compare objects in Java, you should use the equals()
method. The operator ==
is used to compare references, not values, in Java objects.
For example:
String s1 = "hello";
String s2 = new String("hello");
boolean comp = s1.equals(s2); // correct, returns true
comp = s1 == s2; // wrong, returns false
The '==' operator compares two Object references. So, in the case of two Strings, it is examining those objects, and seeing if they represent the same location in memory.
The .equals() method compares the Strings' contents to each other.
Comparing objects, == operator compares if the references are the same. In primitive types (int, float, double, boolean) it actually compares the value. Since Strings are objects, it's better to use the equals() method. == will compare if both references of strings are the same, which may not. equals() method is also used by Java Collections.
精彩评论