Home > Java > javaTutorial > Why Does `0123` Print `83` in Java, But `123` Prints `123`?

Why Does `0123` Print `83` in Java, But `123` Prints `123`?

DDD
Release: 2024-12-27 13:13:16
Original
324 people have browsed it

Why Does `0123` Print `83` in Java, But `123` Prints `123`?

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template