Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 645
Oliver Spryn Avatar asked Dec 13 '11 05:12

Oliver Spryn


People also ask

Does != Work in Java?

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.

Why use .equals instead of == Java?

== 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.

How do you know if two strings are not equal?

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.

Why does == not work for strings in Java?

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.


2 Answers

if (!"success".equals(statusCheck)) 
like image 140
勿绮语 Avatar answered Sep 19 '22 16:09

勿绮语


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

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

like image 36
Jens Schauder Avatar answered Sep 20 '22 16:09

Jens Schauder