Computer Science Canada

String problem... again..

Author:  MysticVegeta [ Fri Dec 16, 2005 12:11 pm ]
Post subject:  String problem... again..

This is really weird. I dont know whats going on! I go soemthing like this
code:
String a = "abcde";
String ab = a.substring(1,2);
System.out.println(ab);
if (ab == "a") {
System.out.println (a);
//doesnt go here!!!
}


Note: Pseudocode, anyways, what is the problem, ab = "a" but "a" not= ab? what the hell?

Author:  Tony [ Fri Dec 16, 2005 12:41 pm ]
Post subject: 

common mistake in Java.

ab is an object of class String, while "a" is a string native value.

== checks for equality, but Object instance is not the same as an instance of a value. You have to compare their content explicitly.

Something like ab.equals("a")

It's been a while since I've done Java

Author:  wtd [ Fri Dec 16, 2005 2:50 pm ]
Post subject: 

Tony wrote:
common mistake in Java.

ab is an object of class String, while "a" is a string native value.


Wrong.

Strings are always objects. The thing is, "==" on objects checks to see if they're exactly the same object, not that their contents are identical.

As mentioned, use the "equals" method.

Author:  Tony [ Fri Dec 16, 2005 3:34 pm ]
Post subject: 

Smile

Author:  MysticVegeta [ Fri Dec 16, 2005 4:29 pm ]
Post subject: 

omg you are joking!! I thought .equals and "==" meant the same! Why do they have to make it so confusing?!

Author:  wtd [ Fri Dec 16, 2005 6:27 pm ]
Post subject: 

MysticVegeta wrote:
omg you are joking!! I thought .equals and "==" meant the same! Why do they have to make it so confusing?!


Because there's no operator overloading.


: