7
class test{
  public static void main(String args[]){
     int a = 011;
     System.out.println(a);
  }
}

Why I am getting 9 as output instead of 011?

How can I get 011 as output?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Dhanuka Perera
  • 1,395
  • 3
  • 19
  • 29
  • `String.format("%02d", a)` – MadProgrammer Feb 20 '16 at 09:24
  • 1
    011 is a literal in base 8, so in base 10 you get 9=(8^1+8^0). see http://stackoverflow.com/a/7218803/5166645 for more details – cobarzan Feb 20 '16 at 09:28
  • numbers that start with 0 are called hex numbers. – SmashCode Feb 20 '16 at 12:25
  • @SmashCode not exactly. Numbers written with a leading "0" in Java are called **octal** and are base 8 (octa- is the Greek prefix for 8). Numbers written with a leading "0x" are called **hexadecimal** (hex for short) and are base 16 (hexa- is the Greek prefix for 6 and deci- is the Latin prefix for 10). Regular numbers are called **decimal** because they are base 10. Octal and hexadecimal are useful because they are much easier to convert to binary than decimal. – cbarrick Jun 28 '16 at 19:01

3 Answers3

9

The JLS 3.10.1 describes 4 ways to define integers.

An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).

An octal numeral consists of a digit 0 followed by one or more of the digits 0 through 7 ...

A decimal numeral is either the single digit 0, representing the integer zero, or consists of an digit from 1 to 9 optionally followed by one or more digits from 0 to 9 ...

In summary if your integer literal (i.e. 011) starts with a 0, then java will assume it's an octal notation.

octal conversion example

Solutions:

If you want your integer to hold the value 11, then don't be fancy, just assign 11. After all, the notation doesn't change anything to the value. I mean, from a mathematical point of view 11 = 011 = 11,0.

int a = 11;

The formatting only matters when you print it (or when you convert your int to a String).

String with3digits = String.format("%03d", a);
System.out.println(with3digits);

The formatter "%03d" is used to add leading zeroes.

formatter

Alternatively, you could do it in 1 line, using the printf method.

System.out.printf("%03d", a);
Community
  • 1
  • 1
bvdb
  • 22,839
  • 10
  • 110
  • 123
2

A numeric literal that starts with 0 is parsed as an octal number (i.e. radix 8). 011 is 9 in octal.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

The 011 is being interpreted as an octal number. This means it's in base 8. See also this SO post. From the accepted answer by Stuart Cook:

In Java and several other languages, an integer literal beginning with 0 is interpreted as an octal (base 8) quantity.

Digits in Base 10:
100s, 10s, 1s

Digits in Base 8:
64s, 8s, 1s

So the 011 is interpreted as 8+1=9

Community
  • 1
  • 1
Arc676
  • 4,445
  • 3
  • 28
  • 44