Reputation: 2459
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?
Upvotes: 0
Views: 1029
Reputation: 16711
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);
Upvotes: 2
Reputation: 314
Yes, it follows the PEMDAS rule and it also truncates answers (cuts off digits after the decimal place without rounding).
Upvotes: 1
Reputation: 6765
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
.
Upvotes: 0