-5
import java.io.*;

    public class StringTest{
        public static void main(String[] args){

            String a="Hello";
            String b="Hello";

            String c=new String("Hello");
            String d=new String("Hello");

            System.out.println(a+c);  
            System.out.println(b+d);  
            System.out.println((a+c)==(b+d));
        }
    }

Why this System.out.println((a+c)==(b+d)); statement returning false?

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
M.Kishore
  • 1
  • 1

1 Answers1

1

Because String is a class, and because of that, the == operator checks for reference equality. Use the equals(Object) method instead. (that is: (a + c).equals(b + d);)

sara
  • 3,521
  • 14
  • 34
  • 2
    There are so many answers in `stackOverFlow` regarding this question. – Ruchira Gayan Ranaweera Aug 12 '15 at 06:22
  • if i compare a==c then the '==' checks for the reference and it will return true so the same thing should happen for this ((a+c)==(b+d)) statement also right? – M.Kishore Aug 12 '15 at 06:27
  • @M.Kishore no, the only comparison that returns true should be `a==b`, because these objects will be pointing to the same String instance (they are both String literals). The `new String("Hello")` will force that the String will be created as a new Object. [read this](http://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext) – SomeJavaGuy Aug 12 '15 at 06:34
  • Yes. It would print `true` if the references were equal. But they aren't, so it doesn't. The two string concatenations produce different objects. They are "equal" ... but not the same object. – Stephen C Aug 12 '15 at 06:34