Do changes emphasize the behavior of integers?

Why is 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)); 

enter this output [0, 1, 10, 1, 100, 8, 1] ?

Why is there 8 in the output? Do some secret functions underline?

+5
source share
6 answers

Integers in the code starting with "0" are interpreted using the Octal system instead of the decimal system.

So, your 010 in Octal is equivalent to 8 in decimal format.

Your 0_1 and your 0_0_1 are also interpreted in this way, but you cannot 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" (therefore, 0x10 is equivalent to 16 in the decimal system) and Binary with the prefix "0x" (therefore, 0b10 is equivalent to 2 in the decimal system).

+4
source

You did not separate integers. When you cast a numeric literal from 0, you get octal numbers. therefore, 0_1_0 = 8 in octal and 0_1 and 0_0_1 both still 1.

Take a look at Java 7 underscore in numeric literals for a deeper answer.

+2
source

Underscores improve readability .

Some examples:

 long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; 

Strange behavior is associated with the octal notation of numbers, which always starts from zero.

+1
source

You used octal notation for the last two. This is actually not unique to Java. If you have a leading zero in front of some integer, it will be counted in octal.

What is octal? This is a basic counting system. We humans use basic system 10 when we count from 0 to 9 and move on to the next digit every time we take step 9 in the previous digit. An octal is the same, except that rollover occurs when you walk past 7.

Consider the binary code, which is the base 2. Your numbers are 1 and 0, and step by step 1 will cause the digit in place to exceed the next step.

 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 
0
source

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

0
source

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

0
source

All Articles