-2

Possible Duplicates:
Strings in Java : equals vs ==
Comparing strings 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?

Community
  • 1
  • 1
shanky
  • 105
  • 1
  • 3

4 Answers4

3

== will not compare the value of the String but its addresse. If you want to compare the value use the method equals().

Cygnusx1
  • 5,329
  • 2
  • 27
  • 39
1

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
MByD
  • 135,866
  • 28
  • 264
  • 277
  • true but, yo usually would not use the new Keyword, and therefore the String would be added to the pool of Strings and s1 == s2 would be true. – Oscar Gomez Aug 04 '11 at 17:56
  • @Oscar Gomez - I used it to avoid using a long example with String input which seems unnecessary to me. – MByD Aug 04 '11 at 17:58
0

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.

Sam DeHaan
  • 10,246
  • 2
  • 40
  • 48
0

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.

HackerGil
  • 1,562
  • 2
  • 11
  • 12