2

So to print the numbers from 1 to 10 we write a simple for loop from i=1 to i<=10 and expect to see the numbers 1 2 3.. 10 printed out. I was curious what happens if I add extra zeros to the condition like so:

for(int i=000000; i<000010; i++){
    System.out.println(i)
}

The output I got was

0
1
2
3
4
5
6
7

Why are these numbers being printed?

Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59
  • 1
    When you have leading zero, it treats as octal – ngunha02 Sep 27 '14 at 03:11
  • Interesting. Is there a way to have it treated as an integer so that instead of iterating from 1 to 10 it iterates from 000001 to 0000010? – Jeremy Fisher Sep 27 '14 at 03:13
  • 1
    Not use leading zeros? Or you can do: for(int i = Integer.parseInt("000000", 10); i < Integer.parseInt("000010",10); i++){ System.out.println(i); } – ngunha02 Sep 27 '14 at 03:20

1 Answers1

5

Literals starting with 0 are considered octal literals, a.k.a base-8 integers.

To calculate its decimal value: 010 = 1 * (8 ^ 1) + 0 * (8 ^ 0). That's 8, so your loop ended when i reached 8.

http://en.wikipedia.org/wiki/Octal

qingbo
  • 2,130
  • 16
  • 19