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

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.

5
if (!"success".equals(statusCheck))
2

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

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

1

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.

4

do the one of these.

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

      or

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

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

Here are more details.

1

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")) {
2

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

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest