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?
This is because integer literals with a leading zero are octal integers (base 8):
1 * 8^3 + 2 * 8^2 + 3 * 8 + 4 = 668
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.)
Leading zero means an octal (base 8) number. 1234 on base-8 is 668.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With