[java] Java Does Not Equal (!=) Not Working?

Here is my code snippet:

public void joinRoom(String room) throws MulticasterJoinException {
  String statusCheck = this.transmit("room", "join", room + "," + this.groupMax + "," + this.uniqueID);

  if (statusCheck != "success") {
    throw new MulticasterJoinException(statusCheck, this.PAppletRef);
  }
}

However for some reason, if (statusCheck != "success") is returning false, and thereby throwing the MulticasterJoinException.

This question is related to java

The answer is


== and != work on object identity. While the two Strings have the same value, they are actually two different objects.

use !"success".equals(statusCheck) instead.


You need to use the method equals() when comparing a string, otherwise you're just comparing the object references to each other, so in your case you want:

if (!statusCheck.equals("success")) {

you can use equals() method to statisfy your demands. == in java programming language has a different meaning!


do the one of these.

   if(!statusCheck.equals("success"))
    {
        //do something
    }

      or

    if(!"success".equals(statusCheck))
    {
        //do something
    }

Sure, you can use equals if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:

if ("success" != statusCheck.intern())

intern method is part of standard Java String API.


Please use !statusCheck.equals("success") instead of !=.

Here are more details.