0
int a=012;
int b=13;
System.out.println(a+b);

The result of the print is 23, so one of them must have been declared in another base format. Which one is this and why?

Martin W
  • 4,548
  • 3
  • 16
  • 27

3 Answers3

4

That's because your variable a is in base-8 , so a is 0*8^2+1*8^1+2*8^0 (^ means power) , so a=10 in decimal base and that's why your answer is 23.

If you want it to be in base 10 just delete the 0 in a=012.

E. Armand
  • 55
  • 5
1

Well, you can easily test it whats the base 10 of that number by simply:

System.out.println(Integer.toString(a,10)); // print in the console

All the rest is explained well by E. Armand, ie. how to convert base8 number to base10.

MS90
  • 1,219
  • 1
  • 8
  • 17
  • 1
    Wouldn't `System.out.println(a);` be a much shorter and more familiar way of showing a base-10 number? – Erwin Bolwidt Dec 09 '18 at 12:09
  • Sure, even from his Q. it could be denoted, but I thought it would be more concise to him doing it the way I did. He could later go and explore what's binary presentation of that octal by calling Integer.toString(012,2). @ErwinBolwidt – MS90 Dec 09 '18 at 12:17
0
int a = 012;  // first '0' means that this number is octal (=10 in decimal)
int b = 13;
System.out.println(a+b);  // 012 + 13 = 10 + 13 = 23.

To change output, do use Integer.toString(int i, int radix):

System.out.println("binary: 0b" + Integer.toString(a + b, 2)); // binary: 0b10111
System.out.println("octal: 0" + Integer.toString(a + b, 8));   // octal: 027
System.out.println("dec: " + Integer.toString(a + b, 10));     // dec: 23
System.out.println("hex: 0x" + Integer.toString(a + b, 16));   // hex: 0x17
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35