...
The noncompliant code example accepts a value from the user without validating it. If this value is greater than 255, it will result in a wrap around. For instance, write(305) will print '1' since the lower order bits of 305 are preserved while the top 24 order bits are lost (305 is 0x131 in Hex so the last hex digit '1' is displayed). That is, the result is remainder modulo 256 of the absolute value of the input.
Code Block | ||
---|---|---|
| ||
class ConsoleWrite {
public static void main(String[] args) {
//Any input value > 255 will result in unexpected output
System.out.write(Integer.valueOf(args[0].toString()));
System.out.flush();
}
}
|
...
Alternatively, perform input validation. While this particular solution will still not display the integer
correctly, it will behave well when the corresponding read
method is utilized to convert the byte back to an integer
.
Code Block | ||
---|---|---|
| ||
class ConsoleWrite { public static void main(String[] args) { //Perform input validation if(Integer.valueOf(args[0]) <= 255) { System.out.write(Integer.valueOf(args[0].toString())); System.out.flush(); } else { //handle error throw new ArithmeticException("Value is out of range"); } } } |
...