0

i'm written a code that reads a line from the socket.
if the line is "bye" i want it to output "nice". from some reason it doesn't work, although i did try to output the input with no conditions and it did says "bye"

this is my code

                String input = null;
                if (socket.getInputStream().available() > 0)                    
                    input = in.readLine();                                                                  

                if (input != null)
                {
                    input = input.trim();
                    if (input == "bye")
                        out.println("nice");

                    out.println(input);
                }
user207421
  • 305,947
  • 44
  • 307
  • 483
Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154
  • possible duplicate of [Java String.equals versus ==](http://stackoverflow.com/questions/767372/java-string-equals-versus) – Matt Ball May 10 '12 at 18:10

3 Answers3

8

Use String#equals(), not ==, to compare strings.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0
if (input != null)
                {
                    input = input.trim();
                    if (input.equals("bye"))
                        out.println("nice");

                    out.println(input);
                }

The equals() compares the content of string.

Ravi Jain
  • 1,452
  • 2
  • 17
  • 41
0

You want your inner if to say this:

if (input.equals("bye"))

instead of

if (input == "bye")

The == is actually comparing the reference object (sort of like a pointer) and may sometimes work when the string is interned, but that's another topic. Use .equals()!

ametren
  • 2,186
  • 15
  • 19