1

See the following example:

int a = 0111;

System.out.println(a);

Output: 73

Why is this happening and how can i get the exact value without conversion?

Biswas Khayargoli
  • 976
  • 1
  • 11
  • 29

2 Answers2

3

According to the Java Language Specification 3.10.1. Integer Literals, there are 4 ways to write an integer literal:

  • DecimalNumeral: Digit 1-9 followed by zero or more digits 0-9, or the number 0.
  • HexNumeral: Leading 0x followed by one or more hexadecimal digits (0-9, a-f). Not case-sensitive.
  • OctalNumeral: Digit 0 followed by one or more digits 0-7.
  • BinaryNumeral: Leading 0b followed by one or more digits 0 or 1. Not case-sensitive.

(All 4 allow underscores for clarity)

As you can see, the number 111 depends on the prefix:
0111 (OctalNumeral) is 1*8*8 + 1*8 + 1 = 64+8+1 = 73.
111 (DecimalNumeral) is 1*10*10 + 1*10 + 1 = 100+10+1 = 111.
0b111 (BinaryNumeral) is 1*2*2 + 1*2 + 1 = 4+2+1 = 7.
0x111 (HexNumeral) is 1*16*16 + 1*16 + 1 = 256+16+1 = 273.

Which one is right depends on what you wanted.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • 1
    How to stop the conversion and get the exact output as 0111 ? – Kishor Bikram Oli Jun 02 '16 at 07:33
  • Getting a leading zero on *output* is a formatting problem. Number don't have leading zeroes. To get leading zero on output, use `printf("%04d", 111)` or the underlying `s = String.format("%04d", 111)`. – Andreas Jun 02 '16 at 07:46
2

Well you're getting the precise value. The problem is the format.

0111

gets interpreted as octal value in java. So your value actually is 73 as a quick calculation would show.

A octal value in java is defined this way:

OctalNumeral:
    0 OctalDigits
    0 Underscores OctalDigits

jls 3.10.1

So 0_111 would be interpreted in the same way.

The format to use in java code would be:

0b111

Which actually gets interpreted as 7 - in binary format - , as expected.

I'll add the links later on, I'm in a bit of a hurry.