Why does this code
int[] a = {
0,
1,
1_0,
0_1,
1_0_0,
0_1_0,
0_0_1
};
System.out.println(Arrays.toString(a));
yield this output [0, 1, 10, 1, 100, 8, 1]
?
Why is there an 8 in the output? Do underscores add some secret functionality?
Integers in your code that start with "0" are interpreted using the Octal system instead of the decimal system.
So your 010 in Octal is equivalent to 8 in Decimal.
Your 0_1 and your 0_0_1 are also interpreted this way, but you can't see it since they all represent 1 in all number systems.
Other number systems that the Java compiler understands are Hexadecimal with the prefix "0x" (so 0x10 is equivalent to 16 in Decimal) and Binary with the prefix "0b" (so 0b10 is equivalent to 2 in Decimal).
You didn't break integers. When you lead the numeric literal with a 0, you end up with octal numbers. so 0_1_0 = 8
in octal and 0_1
and 0_0_1
are both still 1.
Take a look at Java 7 underscore in numeric literals for a more in depth answer.
The underscores only improve readability.
Some examples:
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
The strange behaviour is due to the octal notation of numbers which always starts with a leading zero.
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