Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why int j = 012 giving output 10?

In my actual project It happened accidentally here is my modified small program.

I can't figure out why it is giving output 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 giving output 10.

Then I change 012 to 0123 and now it is giving output 83?

Can anyone explain why?

like image 434
akash Avatar asked Apr 13 '14 06:04

akash


People also ask

Why 012== 10?

Explanation: The value '\012' means the character with value 12 in octal, which is decimal 10.

What is octal number in Java?

Octal is a number system where a number is represented in powers of 8. So all the integers can be represented as an octal number. Also, all the digit in an octal number is between 0 and 7. In java, we can store octal numbers by just adding 0 while initializing.


2 Answers

If a number is leading with 0, the number is interpreted as an octal number, not decimal. Octal values are base 8, decimal base 10.

System.out.println(012):
(2 * 8 ^ 0) + (1 * 8 ^ 1) = 10
12 = 2*8^0 + 1*8^1 ---> 10


System.out.println(0123)
(3 * 8 ^ 0) + (2 * 8 ^ 1) + (1 * 8 ^ 2) = 83
123 = 3*8^0 + 2*8^1 + 1*8^2 ---> 83
like image 123
Amit Avatar answered Sep 27 '22 22:09

Amit


Than I change 012 to 0123 and now it is giving output 83?

Because, it's taken as octal base (8), since that numeral have 0 in leading. So, it's corresponding decimal value is 10.

012 :

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

0123 :

(3 * 8 ^ 0) + (2 * 8 ^ 1) + (1 * 8 ^ 2) = 83
like image 22
Abimaran Kugathasan Avatar answered Sep 27 '22 22:09

Abimaran Kugathasan