views:

84

answers:

2

Why it print the wrong output?

ArrayList<String> loc = new ArrayList<String>();

This arraylist stored the value of:

[topLeft, topLeft, topLeft, bottomLeft, topLeft, bottomLeft, topLeft, topLeft, Left, topLeft]

the firs index 0 is = topLeft

if(loc.get(1)=="topLeft")
   System.out.println("same")

else {
   System.out.println("not same")
}

This program print the wrong output not same instead of same

+3  A: 

Use the equals(Object) method, not the == operator, for example loc.equals("topLeft")

The == operator returns true if two references point to the same Object in memory. The equals(Object o) method checks whether the two objects are equivalent, so will return true if two Strings contain only the same characters in the same order.

Brabster
thank you very much...how can I missed that :-)
Jessy
+1  A: 

String comparison is done by calling str1.equals(str2) rather than using ==.

  • equals(..) compares the strings' contents
  • == compares the references, and they are not the same.

There is a little more to know, however. String objects that are initialized as literals, i.e.

String str = "someString"

instead of via construction (String str = new String("some")) are all the same object. For them == would work.

And finally, for any String, calling intern() returns a String that is the same object as all other strings with the same content. (read intern()'s documentation for more info)

But the best practice here is to use equals(), while being careful if the object you are calling it on (the first string) is not null.

Bozho
Thank you Bozho ..
Jessy