Pharod
Pharod

Reputation: 13

Java char array equality not functioning

I have an assignment that requires use of a socket. On the client and server side I have char[] value= "END STREAM".toCharArray(), which signals the stream to shutdown.

Since I have both these arrays in the 2 different files, my intention is that the client sends the message value > the server. Then the server does the function

while(!Arrays.equals(clientSentence, value))
{
...
inFromClient.read(clientSentence, 0, length);  //to read in from client side
.....
}

In essence, while it does not send the END STREAM message, keep reading. My issue is that the array equality does not work as intended. I even test this by doing

System.out.println(Arrays.equals(value, clientSentence));
System.out.println(new String(value));
System.out.println(new String(clientSentence));

and it prints

false
END STREAM
END STREAM

How can it be false when it is printing the same values. I have made sure that both arrays initialize to the same length so where is it going wrong? I have been stuck on this for hours and searched for answers but cannot find a solution. Thanks

EDIT: added my read function. I use a BufferedReader

Upvotes: 0

Views: 196

Answers (1)

Reuben Tanner
Reuben Tanner

Reputation: 5555

On my box:

char[] x = "END STREAM".toCharArray();
char[] y = "END STREAM".toCharArray();
System.out.println(Arrays.equals(x, y));
System.out.println(Arrays.toString(x));
System.out.println(Arrays.toString(y));

works which makes me think a few things:

  1. The arrays, as declared in your code, are not equal.

  2. There is a character set incompatibility, you said you were using a BufferedReader and, if you're using the Files.newBufferedReader() functionality of Java 1.7, you need specify a charset when using it which may be causing a problem.

  3. End of line issues either from cross platform systems or something else e.g. \r vs \n

Thinking a little more about it...it's probably #2, check this out for further information: http://docs.oracle.com/javase/tutorial/i18n/text/string.html

Upvotes: 1

Related Questions