0

Consider the two following lines of code:

System.out.println((1 + (1 - 1)) / 2);
System.out.println(1 + (1 - 1) / 2);

This is the output that I get:

0
1

Why is this the case? Does Java arithmetic follow PEMDAS rules?

mpmp
  • 2,409
  • 4
  • 33
  • 46
  • 3
    It follows the same rules as in Math, your results were truncated because integer is the default unless otherwise stated. Not just java, pretty much every language follows the rules in Math since they are pretty much created based around Math. – Biu Jan 18 '15 at 23:38
  • Which output did you expect and why? – xehpuk Jan 18 '15 at 23:44
  • I was expecting 1. Malik Brahimi cleared it out for me. I guess I was just delusional and forgot integer/decimal division. – mpmp Jan 18 '15 at 23:50

3 Answers3

2

I don't see the issue, your code does follow PEMDAS. The only issue is that you're not getting 0.5 because you're using integer division. Try this:

System.out.println((1 + (1 - 1)) / 2.0);
System.out.println(1 + (1 - 1) / 2.0);
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
1

Yes, it follows the PEMDAS rule and it also truncates answers (cuts off digits after the decimal place without rounding).

Anthony Palumbo
  • 314
  • 1
  • 11
0

The first one is just (1 + 0)/2 = 1/2 which gives you 0 since you are working with integers.

The second one is 1 + 0/2 = 1 + 0 = 1 which gives you 1.

Oskar Persson
  • 6,605
  • 15
  • 63
  • 124