Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java math sequence (Beginner)

Tags:

java

math

System.out.print(3+2+1-5+4%2-1/4+6);

Output: 7

How does the sequence of performing math operators work? Does Java follow the algebraic PEMDAS or something else?

like image 978
Darwin Avatar asked Sep 05 '26 14:09

Darwin


2 Answers

Yes, Java follows the standard arithmetic order of operations.

However, you may be expecting a different answer than what you got. This is because the value 1/4 is evaluated using integer arithmetic, because both the 1 and the 4 are integers. The result of 1/4 in integer arithmetic is 0.

To ask the compiler to evaluate this using floating point, use something like 1.0/4.0. After doing that, you should get the floating point result 6.75 (which is probably what you expected).

like image 114
Greg Hewgill Avatar answered Sep 08 '26 03:09

Greg Hewgill


Java will follow an order of precedence(order of operations)

  1. ()
  2. *, /, %
  3. +, -

That is all you'll need for this problem but there is more here.

like image 34
KrakenJaws Avatar answered Sep 08 '26 03:09

KrakenJaws



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!