Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: verified NCCEs

...

This noncompliant code example casts the value returned by the read() method directly to a value of type byte and then compares this value with -1 in an attempt to detect the end of the stream. This conversion leaves the value of c as 0xFFFF (e.g., Character.MAX_VALUE) instead of -1. Consequently, the test for the end of stream never evaluates to true (because the char type is unsigned and the value of c is 0-extended to 0x0000FFFF).

Code Block
bgColor#FFcccc
FileInputStream in;
// initialize stream 
byte data;
while ((data = (byte) in.read()) != -1) { 
  // ... 
}

When If the return value of read() method is cast to the byte value 0xFF, the returned byte encounters a 0xFF byte in the file, this value is indistinguishable from the -1 value used to indicate the end of stream, because the byte value is promoted and sign-extended to an int before being compared with -1. Consequently, the loop can halt prematurely if a 0xFF byte is read.

Compliant Solution (byte)

...

This noncompliant code example casts the value of type int returned by the read() method directly to a value of type char, which is then compared with -1 in an attempt to detect the end of stream. This conversion leaves the value of c data as 0xFFFF (e.g., Character.MAX_VALUE) instead of -1. Consequently, the test for the end of stream file never evaluates to true.

Code Block
bgColor#FFcccc
FileReader in;
// initialize stream 
char cdata;
while ((cdata = (char) in.read()) != -1) { 
  // ... 
}

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="59dc8faff7b2f39d-ac29e736-41c7444d-9342978b-46ca4c9278cce9f908586b9a"><ac:plain-text-body><![CDATA[

[[API 2006

AA. References#API 06]]

Class InputStream

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="dc4872cd4d4a7e02-ab74a776-4e424734-a9cfa83e-23ab183bf947bca94bc73017"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. References#JLS 05]]

[§4.2

http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2] Primitive Types and Values

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="07045acf958c0ad0-221bfc7a-44334d6d-a73ba2ea-ff8b1321f75cc599afb0ca84"><ac:plain-text-body><![CDATA[

[[Pugh 2008

AA. References#Pugh 08]]

Waiting for the End

]]></ac:plain-text-body></ac:structured-macro>

...