2

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?

Community
  • 1
  • 1
School Boy
  • 1,207
  • 2
  • 19
  • 33
  • 6
    possible duplicate of [Java Strings: "String s = new String("silly");"](http://stackoverflow.com/q/334518) and [What is the purpose of the expression “new String(…)” in Java?](http://stackoverflow.com/q/390703) and [What is the difference between “text” and new String(“text”) in Java?](http://stackoverflow.com/q/3052442) (by the way, those appeared in top of list of "Related" list on the right hand side which is the same list as you got after entering the question title. In the future, please bother looking into that list) – BalusC Nov 28 '11 at 11:39
  • 1
    indeed, the answer of this question is in the second link : http://stackoverflow.com/q/390703 – Vinze Nov 28 '11 at 11:42
  • Almost this--> http://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext-in-java question. – shift66 Nov 28 '11 at 11:45
  • http://kjetilod.blogspot.com/2008/09/string-constructor-considered-useless.html this is gives one of the possible reason.. – School Boy Nov 28 '11 at 12:21

2 Answers2

3
String one = new String("ONE");

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.

String one = "ONE";
String another_one = "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.

MaxVS
  • 46
  • 1
1

The litera ONE became constant after the compilation. That is, in case two, the two string refer to the same location. That is while they are equal. In the first case the another_one object is explicitly a new object with the content ONE. Dose this make sense.

seanxiaoxiao
  • 1,282
  • 2
  • 11
  • 23