-6
public static void main(String args[]) throws IOException
    {
        String s1="abc";
        String s2="xyz";
        String s3="abcxyz";

        String s4=s1.concat(s2);
        System.out.println(s4);
        @SuppressWarnings("unused")
        String s5=s1+s2;

        if(s3==s4)
        {
            System.out.println("true");
        }
        else
            System.out.println("false");
    }

Why the o/p is coming as false? According to me it should be true. Can someone please explain

2 Answers2

-1

java.lang.String concat() function return new String() object Here s3 and s4 are two different references pointing to two different objects.

== just checks for refernces wheras .equals() checks for the actual content.

s3.equals(s4) will return true.

From javadoc, concat() function.

 public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
-1

== operator compares String value as well as String memory location. Here, s3 and s4 are using different memory locations.

If you want to compare values of String then you should use s3.equals(s4). It will result into true condition.

Chirag Soni
  • 437
  • 2
  • 5
  • 18
Kruti Patel
  • 1,422
  • 2
  • 23
  • 36