Philipp Wendt
Philipp Wendt

Reputation: 2598

Int with leading zeroes - unexpected result

Given the following sample:

public class Main {
    public static void main(String[] args) {
        System.out.println(1234);
        System.out.println(01234);
    }
}

The Output is:

1234
668

Why?

Upvotes: 8

Views: 1162

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500665

This is described in section 3.10.1 of the Java Language Specification. Basically a decimal literal is either just 0, or 1-9 followed by one or more 0-9 characters.

An octal literal is a 0 followed by one or more 0-7 characters.

So 01234 is deemed to be octal.

(Also, interestingly "0" is a decimal literal, but "00" is an octal literal. I can't imagine any situations where that matters, mind you, given that the values are obviously the same.)

Upvotes: 7

Mysticial
Mysticial

Reputation: 471249

This is because integer literals with a leading zero are octal integers (base 8):

1 * 8^3 + 2 * 8^2 + 3 * 8 + 4 = 668

Upvotes: 11

bobbymcr
bobbymcr

Reputation: 24167

A numeric literal with a leading zero is interpreted as octal, i.e. base 8.

Upvotes: 4

MByD
MByD

Reputation: 137332

Leading zero means an octal (base 8) number. 1234 on base-8 is 668.

Upvotes: 4

Related Questions