Niraj Patel
Niraj Patel

Reputation: 2208

regarding leading zero in integer value

I have below code

int a = 01111;
System.out.println("output1 = " + a);
System.out.println("output2 = " + Integer.toOctalString(1111));

and output is

output1 = 585
output2 = 2127

I was expecting output to be like below.

output1 = 2127
output2 = 2127

Why does it give 585 when I print direct int value ? I was expecting java to automatically convert value with leading zero to octal.

What is the relation between 01111 and 585?

Upvotes: 4

Views: 759

Answers (3)

Jiri Kremser
Jiri Kremser

Reputation: 12857

If a number literal starts with 0 it denotes the octal base. Similarly 0x denotes hexadecimal base and 0b the binary number.

So your

int a=01111;

.. is actually

8^3 + 8^2 + 8^1 + 8^0 = 
512 + 64 + 8 + 1 = 585

The Integer.toOctalString(1111)) is actually a reverse function, i.e. the result is the octal number which is 1111 in decimal, which 2127 really is

2127(oct) = 2 × 8^3 + 1 × 8^2 + 2 × 8^1 + 7 × 8^0 = 1111(dec)

Upvotes: 0

Eran
Eran

Reputation: 394156

Leading 0 signifies an octal number (base 8).

01111 (octal) is 1*8^3+1*8^2+1*8^1+1*8^0=585 (decimal)

Integer.toOctalString(1111) converts the decimal number 1111 to an octal String. 2127 octal (2*8^3+1*8^2+2*8^1+7*8^0) is 1111 decimal.

Upvotes: 7

amit
amit

Reputation: 178531

System.out.println("output2 = " +Integer.toOctalString(1111));

Is converting the decimal string 1111 to an octal string: 2127.

The decimal value of the octal 1111, is 585 - as expected, the result is expected, you don't get the same values because the two statements do different things.

A correct test will be:

System.out.println("output2 = " +Integer.toOctalString(a));

Which will give you, as expected, 1111

Upvotes: 4

Related Questions