Home >Java >javaTutorial >Why Does Java Interpret Integer Literals with Leading Zeroes as Octal?
Interpreting Integer Literals with Leading Zeroes
In Java, integer literals with leading zeroes are interpreted as octal (base-8) numbers. This behavior can be puzzling, especially when compared to decimal (base-10) literals.
Consider the following code:
System.out.println(0123); // Prints 83 System.out.println(123); // Prints 123
Explanation:
(1 * 8 * 8) + (2 * 8) + (3) = 83
Therefore, 0123 is interpreted as 83 in decimal.
Avoiding Octal Interpretation:
To avoid unexpected octal interpretations, simply omit the leading zero from integer literals that are not intended to represent octal numbers.
Hexadecimal Literals:
Java also supports hexadecimal (base-16) literals, which are prefixed with 0x. For example:
System.out.println(0x123); // Prints 291
In this case, 0x123 represents the hexadecimal value 123, which is equivalent to 291 in decimal.
The above is the detailed content of Why Does Java Interpret Integer Literals with Leading Zeroes as Octal?. For more information, please follow other related articles on the PHP Chinese website!