0

I don't actually know what's up here, but I am writing server-client application and client sends a string to the server. I need to send the string "x" to the server, so it starts running code1, but when I do it, server runs code3. The funniest thing is System.out.println(x); prints "a" in the console.

Here is a fragment of server code(runs on win7, javac compiler):

sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());

String x = (String) sInput.readObject();
System.out.println(x);

if (x == "a") {
   /* 
    * code1
    */
} else if (x == "b") {
   /* 
    * code2
    */
} else {
   /* 
    * code3
    */
}

And this is what client does(runs osx, javac compiler):

sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());

String x = "a";
sOutput.writeObject(x);

How should I sort it out?

P.S. I know about exception declaration, they are removed to make the code shorter.

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 4
    Don't compare String values using `==`. Use `equals()`. – Alexis C. Feb 17 '14 at 19:47
  • 2
    I hate it when people say that the tool they are using is wrong without any proof. How long has Java been around? How long have you been programming it? Your `if` statement works perfectly well. Your expectations are wrong. – Sotirios Delimanolis Feb 17 '14 at 19:47
  • Using `==` instead of `equals` is a classic newbie mistake. You'll probably make it two or three more times, but fix in your head the point that there's (almost) always a logical explanation, and it's (almost) always due to a "stupid" mistake. – Hot Licks Feb 17 '14 at 19:53
  • 1
    And it's better to use the Yoda form, like `if ("a".equals(x))` in case `x` is `null` – Mike B Feb 17 '14 at 19:54

2 Answers2

1

Use equals method to compare the values of two strings. See How do I compare strings in Java? for more information.

Community
  • 1
  • 1
Girish
  • 1,717
  • 1
  • 18
  • 30
0

The “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

The equals method is actually meant to compare the contents of 2 objects, and not their location in memory. Source - http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

And since Strings are non-mutable and use a different memory location every time they are instantiated, they are better always compared using equals() method :)

Atul O Holic
  • 6,692
  • 4
  • 39
  • 74