0

Just starting with Java. Could not find the answer in google. Could someone please explain why result of this operation:

System.out.println(20 + -3 * 5 / 8));

is: 19?

I assume by default it will print out an integer result only, but why it is rounded up? As the result is 18.125, so I would expect 18 to be printed. Is it always rounding integers up?

Thanks!

Lukas
  • 292
  • 1
  • 3
  • 12

3 Answers3

2

The associativity of

20 + -3 * 5 / 8

is such that it's equivalent to

20 + (-3 * 5 / 8)

(-3 * 5 / 8) is rounded towards zero, so it is -1; hence 20+(-1) is 19.

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
  • 1
    Is "rounded" the correct term here? Since Integer can not hold any floating numbers it simply drops them. – Murat Karagöz Oct 24 '18 at 09:00
  • @MuratKaragöz ["Integer division rounds toward 0"](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.17.2). Yep. – Andy Turner Oct 24 '18 at 09:01
  • Okay thank you @murat Karagoz, so (-3*5/8) = -1.85 and it drops the 0.85. Now it make sense! – Lukas Oct 24 '18 at 09:02
1

Sure. The reason is that integer division rounds towards zero. So the order of the operations is like this.

-3 * 5 = -15
-15 / 8 = -1 (rounded towards zero)
20 + -1 = 19
Dawood ibn Kareem
  • 68,796
  • 13
  • 85
  • 101
1

Just as a matter of interest, you could retain the value you want by using the BigDecimal operations to get the right result:

BigDecimal resultValue = BigDecimal.valueOf(-3).multiply(BigDecimal.valueOf(5)).divide(BigDecimal.valueOf(8));      
System.out.println(20 + resultValue.doubleValue());
Vankuisher
  • 76
  • 8
  • Thanks for the comment! The question was only my curiosity, why this is happening rather then how to get the accurate value, but thank you anyway :) – Lukas Oct 24 '18 at 13:43