Why is Java's division broken?

Java is a strongly typed language so you should be aware of the types of the values in expressions. If not...

1 is an int (as 2), so 1/2 is the integer division of 1 and 2, so the result is 0 as an int. Then the result is converted to a corresponding double value, so 0.0.

Integer division is different than float division, as in math (natural numbers division is different than real numbers division).


You are thinking like a PHP developer; PHP is dynamically typed language. This means that types are deduced at run-time, so a fraction cannot logically produce a whole number, thus a double (or float) is implied from the division operation.

Java, C, C++, C# and many other languages are strongly typed languages, so when an integer is divided by an integer you get an integer back, 100/50 gives me back 2, just like 100/45 gives me 2, because 100/45 is actually 2.2222..., truncate the decimal to get a whole number (integer division) and you get 2.

In a strongly typed language, if you want a result to be what you expect, you need to be explicit (or implicit), which is why having one of your parameters in your division operation be a double or float will result in floating point division (which gives back fractions).

So in Java, you could do one of the following to get a fractional number:

double result = 1.0 / 2;
double result = 1f / 2;
double result = (float)1 / 2;

Going from a loosely typed, dynamic language to a strongly typed, static language can be jarring, but there's no need to be scared. Just understand that you have to take extra care with validation beyond input, you also have to validate types.

Going from PHP to Java, you should know you can not do something like this:

$result = "2.0";
$result = "1.0" / $result;
echo $result * 3;

In PHP, this would produce the output 1.5 (since (1/2)*3 == 1.5), but in Java,

String result = "2.0";
result = "1.0" / result;
System.out.println(result * 1.5);

This will result in an error because you cannot divide a string (it's not a number).

Hope that can help.