-3

Why the following java code gives answer as:

not equal
equal.

Code:

    String a=new String("abc");
    String b=new String("abc");
    String c="abc";
    String d="abc";


    if(a==b){
        System.out.println("equal");
    }else{
        System.out.println("not equal");
    }

    if(c==d){
        System.out.println("equal");
    }else{
        System.out.println("not equal");
    }

I am confused as to what is the way the two statements

        String a=new String("abc");
        String c="abc";

differ in ?
In simple words what is the difference between the two assignments ?
Any help will be appreciated.
Thanks

Nagesh Salunke
  • 1,278
  • 3
  • 14
  • 37
  • 5
    This has been asked **many** times before. Here is one explanation: http://stackoverflow.com/a/334613/367273 – NPE Apr 12 '13 at 19:33
  • 1
    You should look at [String.intern()](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern%28%29) and research it carefully. `All literal strings and string-valued constant expressions are interned.` – OldCurmudgeon Apr 12 '13 at 19:34

3 Answers3

3

When you use a string literal to directly initialize a string variable, Java will intern the Java literal string, so that both string variables refer to the same actual string object.

When you use the new operator, you get a different object, even if the contents of the new string is the same as the string literal.

And as has been pointed out many times, the == operator compares object references to see if they point to the same object, and does not compare string contents.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

Don't use == to compare strings; use equals() method.

if(a.equals(b)) {
    System.out.println("equal");
}else{
    System.out.println("not equal");
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
1

Assigning a string literal will utilize the string pool (hence the equal reference), newing a String will always create a new instance which results in different objects.

atamanroman
  • 11,607
  • 7
  • 57
  • 81