Puzzling Behavior of Integer Literals with Leading Zeroes
In Java, integer literals with leading zeroes exhibit unexpected behavior, as exemplified by the following code snippets:
System.out.println(0123); // Prints 83 System.out.println(123); // Prints 123
Reason for the Difference
The key to understanding this difference lies in octal representation. A leading zero in an integer literal signals that the literal is expressed in base 8 (octal). In octal, each digit represents a power of 8, starting from 0.
Thus, the literal 0123 can be converted to decimal as follows:
(0 * 8³) + (1 * 8²) + (2 * 8) + (3) = 83
In contrast, the literal 123 is interpreted in decimal, where each digit represents a power of 10. Therefore, it evaluates to 123.
Hexadecimal Literals
In addition to octal, Java also supports hexadecimal (base 16) literals using the 0x prefix. For instance, 0xFF represents the hexadecimal number 255, which is equal to 11111111 in binary.
Recommendation
To avoid confusion, it is advisable to omit leading zeroes from integer literals unless octal representation is explicitly intended. Otherwise, the literal will be misinterpreted as octal, leading to unexpected results.
The above is the detailed content of Why Does `0123` Print `83` in Java, But `123` Prints `123`?. For more information, please follow other related articles on the PHP Chinese website!