Home >Java >javaTutorial >Why Does Java Interpret Integer Literals with Leading Zeroes as Octal?

Why Does Java Interpret Integer Literals with Leading Zeroes as Octal?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 11:18:12901browse

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:

  • 0123 begins with a leading zero, indicating an octal literal. To convert from octal to decimal, multiply each digit by the corresponding power of 8 and sum the results:
(1 * 8 * 8) + (2 * 8) + (3) = 83

Therefore, 0123 is interpreted as 83 in decimal.

  • 123 has no leading zero, so it is interpreted as a decimal literal, resulting in the expected value of 123.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn