0

I am sending a message via a DatagramChannel as follows:

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
String request_message = "request";
buf.put(request_message.getBytes());
buf.flip();

int bytesSent = udpserver.send(buf, successor_port_1); // udpserver is a DatagramChannel

I then read the message on the server:

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();

String message = new String(buf.array(), Charset.forName("UTF-8"));
System.out.println(message); //print message for testing purposes

if (message == "request"){
    //code here does not get executed
 }

The problem is, my code doesn't enter the "if" statement even though message = "request" which also seems to be confirmed by my print statement.

Any help would be appreciated!

user207421
  • 305,947
  • 44
  • 307
  • 483
  • String comparison has nothing to do with networking. String comparison is used everywhere. It should not be handeled as a TCP/IP specific feature. It is data marshaling feature. – Val Apr 11 '13 at 16:37

1 Answers1

1

The reason for this is that Strings in java need to be compared with .equals, so your test should be:

if (message.equals("request")){

This is because, in Java, == tests whether two object are the same instance (it tests reference equality - do both the references point to the same memory) rather than equal.

You can carry out a quick test:

System.out.println("request" == new String("request"));

Output:

false

For more information read this SO answer.

Community
  • 1
  • 1
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166