-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?

0

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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 - I used it to avoid using a long example with String input which seems unnecessary to me.
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.