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)
When one of the operands to a division is a double and the other is an int, Java implicitly (i.e. behind your back) casts the int operand to a double. Thus, Java performs the real division 7.0 / 3.0.
Be careful when performing integer division. When dividing an integer by an integer, the answer will be an integer (not rounded). When an operation involves two types (as the mixed division shown above), the smaller type is converted to the larger type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With