jjnguy
jjnguy

Reputation: 138874

Java int division confusing me

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)

Upvotes: 9

Views: 1958

Answers (3)

divesh premdeep
divesh premdeep

Reputation: 1070

Observed an interesting behavior here.

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

Howzzat ?!

Upvotes: 1

moogs
moogs

Reputation: 8202

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

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

Upvotes: 6

Greg Hewgill
Greg Hewgill

Reputation: 993085

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.

Upvotes: 21

Related Questions