Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do underscores alter the behaviour of Integers? [duplicate]

Tags:

java

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?

like image 637
Bassdrop Cumberwubwubwub Avatar asked Jul 15 '15 13:07

Bassdrop Cumberwubwubwub


3 Answers

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

like image 54
mhlz Avatar answered Nov 10 '22 00:11

mhlz


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.

like image 37
jkeuhlen Avatar answered Nov 10 '22 00:11

jkeuhlen


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.

like image 44
Willi Mentzel Avatar answered Nov 10 '22 01:11

Willi Mentzel