Possible Duplicate:
Java Strings: “String s = new String(”silly“);”
I was going through some of the string examples and I am confused:
What is the difference between
String one = new String("ONE");
and
String one = "ONE";
and here is the example why i am bit confused
String one = new String("ONE");
String another_one = new String("ONE");
System.out.print(one.equals(another_one)); //-->true
System.out.print(one == another_one ); //-->false
while
String one = "ONE";
String another_one = "ONE";
System.out.print(one.equals(another_one)); //-->true
System.out.print(one == another_one ); //-->true
Why is it such so?
Creates a new object. Comparing using the equals method compares the string of characters itself, when they are exactly the same it returns true. Comparing using the “==” operator compares the objects, which in this case are not the same since you created a new one.
This does infact not create a new object, the compiler will optimise these two statements so that both “one” and “another_one” point to the same object in memory as they both reference the same string literal. Since here both variables point to the very same object, the “==” will return true in this case.