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
.
Note: When comparing two strings in java, we should not use the == or != operators. These operators actually test references, and since multiple String objects can represent the same String, this is liable to give the wrong answer.
== should be used during reference comparison. == checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.
Use the strict inequality (! ==) operator to check if two strings are not equal to one another, e.g. a !== b . The strict inequality operator returns true if the strings are not equal and false otherwise.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
if (!"success".equals(statusCheck))
==
and !=
work on object identity. While the two String
s have the same value, they are actually two different objects.
use !"success".equals(statusCheck)
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With