[java] If statement with String comparison fails

I really don't know why the if statement below is not executing:

if (s == "/quit")
{
    System.out.println("quitted");
}

Below is the whole class.

It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out.

Thanks for looking :)

class TextParser extends Thread {
    public void run() {
        while (true) {
            for(int i = 0; i < connectionList.size(); i++) {
                try {               
                    System.out.println("reading " + i);
                    Connection c = connectionList.elementAt(i); 
                    Thread.sleep(200);

                    System.out.println("reading " + i);

                    String s = "";

                    if (c.in.ready() == true) {
                        s = c.in.readLine();
                        //System.out.println(i + "> "+ s);

                        if (s == "/quit") {
                            System.out.println("quitted");
                        }

                        if(! s.equals("")) {
                            for(int j = 0; j < connectionList.size(); j++) {
                                Connection c2 = connectionList.elementAt(j);
                                c2.out.println(s);
                            }
                        }
                    }
                } catch(Exception e){
                    System.out.println("reading error");
                }
            }
        }
    }
}

This question is related to java multithreading if-statement string-comparison

The answer is


You can use

if("/quit".equals(s))
   ...

or

if("/quit".compareTo(s) == 0) 
    ...

The latter makes a lexicographic comparison, and will return 0 if the two strings are the same.


If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.


You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.


Strings in java are objects, so when comparing with ==, you are comparing references, rather than values. The correct way is to use equals().

However, there is a way. If you want to compare String objects using the == operator, you can make use of the way the JVM copes with strings. For example:

String a = "aaa";
String b = "aaa";
boolean b = a == b;

b would be true. Why?

Because the JVM has a table of String constants. So whenever you use string literals (quotes "), the virtual machine returns the same objects, and therefore == returns true.

You can use the same "table" even with non-literal strings by using the intern() method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:

String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.


To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:

In Java there are many string comparisons.

String s = "something", t = "maybe something else";
if (s == t)      // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>

In your example you are comparing the string objects, not their content.

Your comparison should be :

if (s.equals("/quit"))

Or if s string nullity doesn't mind / or you really don't like NPEs:

if ("/quit".equals(s))

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to multithreading

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Waiting until the task finishes What is the difference between Task.Run() and Task.Factory.StartNew() Why is setState in reactjs Async instead of Sync? What exactly is std::atomic? Calling async method on button click WAITING at sun.misc.Unsafe.park(Native Method) How to use background thread in swift? What is the use of static synchronized method in java? Locking pattern for proper use of .NET MemoryCache

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to string-comparison

How do I compare two strings in python? How to compare the contents of two string objects in PowerShell String comparison in bash. [[: not found How do I compare version numbers in Python? Test if a string contains a word in PHP? Checking whether a string starts with XXXX comparing two strings in SQL Server Getting the closest string match How can I make SQL case sensitive string comparison on MySQL? String Comparison in Java