-3

Possible Duplicate:
Java String.equals versus ==

public class S_eaqual {
    public static void main(String[] args) {
        String s1 = "one", s2 = "two";
        if (s1 + s2 == "onetwo") {
            System.out.println("Yes..equal");
        }
    }
}

This type of comparison shows errors. Is this not the right way of comparing strings? Two String objects can be compared using == operator. So why this is showing error?

Community
  • 1
  • 1
techi_29
  • 13
  • 1
  • 3
  • 5
    See: http://stackoverflow.com/questions/767372/java-string-equals-versus – Anthony Pegram Dec 30 '11 at 06:22
  • 3
    I tried executing it. I didnt get any error. It just didn't print anything bcos the strings are not equal. Can you tell us the error that you got? – Ryan Dec 30 '11 at 06:25

4 Answers4

4

String should be compared using equals method.

String s1 = "one", s2 = "two";
if("onetwo".equals(s1+s2)) {
  System.out.println("Yes..equal");
}
Vaandu
  • 4,857
  • 12
  • 49
  • 75
3

Try this...

String s3 = s1 + s2
if(s3.equals("onetwo")) {
...

== compares if they refer to the same object, and the result of s1+s2 isn't in this case, and the .equals() method on string compares that the values are the same. In general, you only use == for primitive value comparisons. Although you can do it for objects iff you intend to check to make sure that two references point to the same object.

BillRobertson42
  • 12,602
  • 4
  • 40
  • 57
2

use (s1+s2).equals("onetwo"); instead

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
2

Use equals:

if (s1.concat(s2).equals("onetwo")) System.out.println("Yes..equal");
Larry Williamson
  • 1,149
  • 5
  • 18