2

FindBugs is reporting me that I'm comparing nonnegative value with -1 for the following code.

/* I get inputstreamreader from a org.apache.commons.net.telnet.TelnetClient object */

InputStreamReader reader = telnet.getInputStream();

char msg = 0;
StringBuilder temp = new StringBuilder();
while((msg = (char)reader.read()) != -1){
  temp.append(msg);
} 
System.out.println("Read Message = "+temp.toString());

But when I read through the InputStreamReader.read() documentation it says "Returns: The number of characters read, or -1 if the end of the stream has been reached"

What is it I'm doing wrong here.. ?

Thanks in advance

Ravi Kiran
  • 21
  • 2

3 Answers3

3

char in Java is a single 16-bit Unicode character ranging from 0 to 65,535. It will never be negative.

As a fun exercise check what this prints:

System.out.println(">>>>>>> TEST: " + (int)((char) -1));

And figure out why.

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
2

Reader returns int, which may be negative. But you are casting the value to char, which is nonnegative.

BTW, this method does not return number of characters read, but one character:

Returns: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached (http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html#read%28%29)

pkalinow
  • 1,619
  • 1
  • 17
  • 43
1

The while loop compares a char to a negative integer. This should work:

InputStreamReader reader = telnet.getInputStream();

int data = 0;
StringBuilder temp = new StringBuilder();
while((data = reader.read()) != -1){
    char msg = (char) data;
    temp.append(msg);
} 
System.out.println("Read Message = "+temp.toString());
stefana
  • 2,606
  • 3
  • 29
  • 47