views:

547

answers:

3

I am doing very simple int division and I am getting odd results.

This code prints 2 as expected:

public static void main(String[] args) {
    int i = 200;
    int hundNum = i / 100;
    System.out.println(hundNum);
}

This code prints 1 as not expected:

public static void main(String[] args) {
    int i = 0200;
    int hundNum = i / 100;
    System.out.println(hundNum);
}

What is going on here?

(Windows XP Pro, Java 1.6 running in Eclipse 3.4.1)

+20  A: 

The value 0200 is an octal (base 8) constant. It is equal to 128 (decimal).

From Section 3.10.1 of the Java Language Specification:

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

Greg Hewgill
Wow, I cannot believe I haven't ran into this before. I feel like an idiot. Thanks!
jjnguy
I looked at your rep score and I though it must be something else!
moogs
This is one of the most irritating features of C-based languages. I have never seen someone use an octal constant on purpose, but I've seen it cause problems multiple times.
Mark Bessey
It is a case of Occam's razor. It's usually the simplest solution.
jjnguy
The only time I ever use octal constants on purpose is in the C `mkdir()` function.
Greg Hewgill
+6  A: 

The value 0200 is an octal, which is 128 in decimal.

For further information, see the literals section of the Primitive Data Types explanation.

moogs
+1  A: 

Observed an interesting behavior here.

If I do an Integer.parseInt("0200"), I get 200 as o/p.

Howzzat ?!

divesh premdeep
Well check the API doc for parseInt. It says it all:public static int parseInt(String s) ... Parses the string argument as a signed decimal integer.The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value.
sateesh
parseInt parses a string with radix 10. A call to Integer.decode parses 0200 to 128.
Salandur