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
Release: 2024-12-21 11:18:12
Original
963 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template