Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int with leading zeroes - unexpected result

Tags:

java

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?

like image 651
Philipp Wendt Avatar asked Nov 24 '11 08:11

Philipp Wendt


3 Answers

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

1 * 8^3 + 2 * 8^2 + 3 * 8 + 4 = 668
like image 153
Mysticial Avatar answered Sep 28 '22 01:09

Mysticial


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.)

like image 37
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet


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

like image 39
MByD Avatar answered Sep 28 '22 01:09

MByD