0

I'm a c++ programmer who wrote some php server code to be translated to java and pretty new to Java. But it feels quite common coming from c++. I have a server up and running and this code:

String req = "<xml><version>1</version><test></test></xml>";
Document doc = loadXMLFromString (req);
Element root = doc.getDocumentElement();    // "xml"

// check version
Element e = firstChildElement (root, "version");
String result = e.getTextContent(); // returns "1"!
String expected = "1";
if (result != expected)
{
    out.printLn ("wrong version: (" + result + "), expected: (" + expected + ")!");
    return;
}

This prints "wrong version: (1), expected (1)". The same holds with if (result != "1"). Now even the debugger (eclipse) shows that result is actually "1", so I'm truly lost here. I seem to be missing the obvious but just can't see it...can you help pls? Thanks!

charlie
  • 68
  • 2
  • 8
  • http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – xp500 Jul 15 '15 at 10:39
  • 1
    Correct, one `"1"` is not always `==` another `"1"` in Java. With objects, `==` checks to see if the references are the **same** object, not equivalent ones. For that you use `equals`. ("not always" because with string interning, what seem like two separate objects may actually be the same object.) – T.J. Crowder Jul 15 '15 at 10:40
  • found the answer myself here [Java Does Not Equal (!=) Not Working?](http://stackoverflow.com/questions/8484668/java-does-not-equal-not-working?lq=1). Sorry I had looked before but only explicitly searching for "!=" yielded the result. Sorry for bugging you. – charlie Jul 15 '15 at 10:45
  • Got it, incredibly quick reply, thanks! – charlie Jul 15 '15 at 10:48

1 Answers1

3

Use .equals() to compare String objects.

user1438038
  • 5,821
  • 6
  • 60
  • 94