Why int j = 012 gives output 10?

In my own project, this happened by accident, here is my modified small program.

I can not understand why it gives a conclusion of 10 ?

public class Int { public static void main(String args[]) { int j=012;//accidentaly i put zero System.out.println(j);// prints 10?? } } 

After that, I put two zeros, still outputting 10.

Then I change 012 to 0123 and now it gives 83?

Can anyone explain why?

+9
java integer numbers literals
source share
3 answers

How do I change 012 to 0123 and now it gives output 83?

Because it is taken as an octal base (8), since this number has 0 at the beginning. So the corresponding decimal value is 10

012:

 (2 * 8 ^ 0) + (1 * 8 ^ 1) = 10 

0123:

 (3 * 8 ^ 0) + (2 * 8 ^ 1) + (1 * 8 ^ 2) = 83 
+21
source share

Leading zero means that the number is interpreted as octal , not decimal.

+6
source share

You assign a constant to a variable using the octal representation of a constant of type int. Thus, the compiler gets the integer value from the octal representation 010 by converting it to decimal representation using this algorithm 0 * 8 ^ 0 + 1 + 8 ^ 1 = 10, and then assigns j the value 10. Remember when you see a constant beginning with 0 is an integer in octal representation. that is, 0111 is not one hundred and eleven, but 1 * 8 ^ 0 + 1 * 8 ^ 1 + 1 * 8 ^ 2.

+2
source share

All Articles