Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do math equations work in Java?

When I do something like this

int test = 5 + 3 * (4 - 1) / 2;

I get 9. I suspected this was because int rounds down. However, when I do this

float test = 5 + 3 * (4 - 1) / 2;

I also get 9. However, when I do this

float test1 = 5;
float test2 = 4.5;
float test = test1 + test2;

Test finally outputs 9.5. Could someone explain the logic behind this? Why don't I get 9.5 in the second example? Thanks.

like image 633
glcohen Avatar asked Aug 26 '12 22:08

glcohen


1 Answers

In your second example, although you are assigning the result to a variable of type float, the calculation itself is still performed exactly the same way as the first example. Java does not look at the destination variable type to determine how to calculate the right hand side. In particular, the subexpression 3 * (4 - 1) / 2 results in 4.

To fix this, you can use floating point literals instead of all integers:

float test = 5 + 3 * (4 - 1) / 2.0f;

Using 2.0f triggers floating point calculations for the arithmetic expression.

like image 80
Greg Hewgill Avatar answered Sep 20 '22 07:09

Greg Hewgill