Java Does Not Equal (!=) Not Working?

Java

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

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

Solution 3 - Java

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.

Solution 4 - Java

do the one of these.

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

      or

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

Solution 5 - Java

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

Here are more details.

Solution 6 - Java

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

Solution 7 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOliver SprynView Question on Stackoverflow
Solution 1 - Java勿绮语View Answer on Stackoverflow
Solution 2 - JavaJens SchauderView Answer on Stackoverflow
Solution 3 - JavaPaulView Answer on Stackoverflow
Solution 4 - JavasubodhView Answer on Stackoverflow
Solution 5 - Javalobster1234View Answer on Stackoverflow
Solution 6 - JavaMatt LaceyView Answer on Stackoverflow
Solution 7 - JavazhaoywView Answer on Stackoverflow