I am new to Java, please help me with this:
System.out.println(3 * (4 / 5) * 6);
Why is the answer 0?
I am new to Java, please help me with this:
System.out.println(3 * (4 / 5) * 6);
Why is the answer 0?
Its a simple BODMAS
Expression Evaluation
Evaluation for (3 * (4 / 5) * 6) will be;
1. (4/5)=0
2. 3*0=0
3. 0*6=0
To avoid 0 answer you can modifiy expression as
1. (3 * (4.0 / 5.0) * 6) // return float value
2. (3*4*6)/5 //return integer value
3. (3 * (4/ 5.0) * 6) // return float value
In these cases answer will be non-zero for this expression
(4 / 5)
is 0 because they are integer values and the result of 0,8 is rounded to 0. Do (4f / 5F)
. Now the result will be like expected. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html This is a usefull link for you.
Because you are working with Integers, not floats. 4 / 5
is 0.8
, but an integer cannot store that number, so it is rounded down to 0
. Then the rest of the equation is multiplying numbers by zero, which will always result in 0
.
Turn the numbers into 3.0
, 4.0
, 5.0
, 6.0
to turn the equation into a float-based one.
With integers:
3 * (4 / 5) * 6 = 0
With floats:
3.0 * (4.0 / 5.0) * 6.0 = 14.4
Remember BODMAS rule
first operation will be divide
means 4/5
will be evaluated and it gives 0
(because 4 and 5 are integers and it gives 0) and anything multiplied with 0
gives 0
The "problem" is this term:
(4 / 5)
Because both numbers are int
, the result will be int
. Integer arithmetic in java truncates the fractional part (it doesn't round), so the result will be zero (0.8
will become 0
).
You're using integer division (since 4 and 5 are both int):
4 / 5 == 0 // 4/5 = 0 with remainder equals to 4: 0 * 5 + 4 == 4
that's why the whole formula
3 * (4 / 5) * 6 == 0
If you want 4/5 treated as floating point division and so that it has a result of 0.8 you should use floating point numbers as well: 4.0 and 5.0
System.out.println(3 * (4.0 / 5.0) * 6); // <- 14.4
P.S. It's typical behaviour not only for Java, but for C, C++, C# as well
Because 4/5 = 0 in your case << It is integer division
To fix this, you can rewrite your code as follow\
System.out.println(3 * (4 /
5.0) * 6);
And the result will be
14.400000000000002