5

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?

6 Answers6

4

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

mhlz
  • 3,497
  • 2
  • 23
  • 35
2

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.

Community
  • 1
  • 1
jkeuhlen
  • 4,401
  • 23
  • 36
1

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.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
0

You've used octal notation for those last two. This isn't unique to Java, actually. If you have a leading zero in front of some integer, it will be counted in octal.

What is octal? It is a base-8 system of counting. We humans use a base 10 system when we count, starting at 0, ending at 9, and rolling over to the next digit each time we take a step past 9 in the preceding digit. Octal is the same way, except the rollover happens when you step past 7.

Consider Binary, which is base 2. Your digits are 1 and 0, and stepping past 1 will cause the digit in place to roll over an increment the next.

base2  0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011

base8  0000 0001 0002 0003 0004 0005 0006 0007 0010 0011 0012 0013

base10 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012
scriptocalypse
  • 4,942
  • 2
  • 29
  • 41
0

When you precede a number with a 0, Java treats it as octal. 010 in octal is 8 in decimal.

iobender
  • 3,346
  • 1
  • 17
  • 21
0

In Java and several other languages, an integer literal beginning with 0 is interpreted as an octal (base 8) quantity. See Why is 08 not a valid integer literal in Java?

Community
  • 1
  • 1
Danil Gaponov
  • 1,413
  • 13
  • 23