Reputation: 23012
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?
Upvotes: 14
Views: 27966
Reputation: 665
By placing a zero in front of the number is an integer in octal form. 010 is in octal form so its value is 8
Guess output of this program on your own :
public class sol{
public static void main(String[] args){
int p = 010;
int q = 06;
System.out.println(p);
System.out.println(q);
}
}
output is :
8
6
Upvotes: 1
Reputation: 72
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
Upvotes: 3
Reputation: 32498
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
Upvotes: 25
Reputation: 578
You are assigning a constant to a variable using an octal representation of an type int constant. So the compiler gets the integer value out of the octal representation 010 by converting it to the decimal representation using this algorithm 0*8^0 + 1+8^1 = 10 and then assign j to 10. Remember when you see a constant starting with 0 it's an integer in octal representation. i.e. 0111 is not 1 hundred and 11 but it's 1*8^0 + 1*8^1 + 1*8^2.
Upvotes: 2