Int with leading zeros - unexpected result

Given the following example:

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

Exit:

 1234 668 

Why?

+8
java
source share
4 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 
+11
source share

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

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

So, 01234 is considered octal.

(It’s also interesting that β€œ0” is a decimal literal, but β€œ00” is an octal literal. I cannot imagine situations where it matters, remember, given that the values ​​are obviously the same.)

+7
source share

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

+4
source share

A numeric literal with an initial zero is interpreted as octal, i.e. base 8.

+4
source share

All Articles