The Real Value of an int Variable Starting with 0 in Java

In Java, an int literal starting with 0 is interpreted as an octal (base-8) number. This article explains how Java represents octal integers.

  • Ryan
  • 1 min read
/images/posts/java-octal-int.png

Today, while solving a problem on LeetCode, I accidentally discovered the following issue:

What value does the following Java statement output?

System.out.println(00123);
System.out.println(0_123);

The answer is:

83
83

Why?

I was puzzled at the time, but later found the answer in the Java Language Specification — see the Java 7 Language Specification, which clearly states:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

In other words, for an int starting with 0, Java converts it into octal notation. For 00123, the octal value it represents is: 1×8×8+2×8+3 = 83.

Written by : Ryan

Writing about distributed systems, AI engineering, and production internals.

Recommended for You

The Implementation Details of hashCode()

The Implementation Details of hashCode()

A deep dive into the implementation of Java's hashCode() method, from class loading to hash collision handling.

Understanding the Java String.intern() Memory Model

Understanding the Java String.intern() Memory Model

Calling string.intern() in Java first looks up the corresponding string in the string constant pool; if it doesn't exist, the string is created in the pool and then returned.