2

I am confused why this is and I cannot seem to find an answer why. This is from the assignment:

x=1, y=2, z=3;

z=(int)(x/y*3.0+z*012);

System.out.printf("%d %d %d", x, y, z);

Answer is :

1 2 30; << from eclipse

How I arrived here:

(1/2) = 0 * 3.0 = 0 + (z*012)= 30. I wanted to say 36 but I guess it is 30 according to the IDE.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
JD112
  • 87
  • 1
  • 7

4 Answers4

10

012 is octal number not decimal which decimal value is 10.

z=(int)(x/y*3.0+z*012);

is equals -

z=(int)(1/2*3.0+3*10);
  • For reference

Numeric starts with 0 is octal number.
Numeric starts with 0x is hexadecimal number.
Numeric starts with 0b or OB is binary number.(Since Java edition 7 - Binary Literals)

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • 1
    Thank you for the fast response. Why my professor did not point this out is very strange to me...unless that was the point :) – JD112 Feb 12 '14 at 06:07
4

In Java and several other languages, an integer literal beginning with 0 is interpreted as an octal (base 8) quantity. Here 012 is an octal number which has a decimal value f 10

So your multiplication will come like

z = (int) (1/2 * 3.0 + 3 * 10);

From JLS

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
3

012 is an octal, because it starts with 0:

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

Therefore:

012 * 3 = 10 * 3 = 30

Notes:

  • Remember that an octal is a number in base 8 (decimal is base 10), so it can't have digits larger or equal to 8.
  • Similarly, hexadecimal numbers starts with 0x, for example: 0x12 = 1*16 + 2 = 18
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

See the JLS:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

So,

012 = 0 * 82 + 1 * 81 + 2 * 80 = 10

In Java 7, you can use underscores in numeric literals which might help you interrupting the value.

Maroun
  • 94,125
  • 30
  • 188
  • 241