Just as in math also in Java multiplication and division have higher precedence than addition and subtraction. Therefore your expression is equivalent to the following:
3 + ((4 - 3) / 2)
So let’s just take it step by step:
3 + (4 - 3) / 2 = 3 + ((4 - 3) / 2)
= 3 + (1 / 2)
= 3 + 0
= 3
As others have said, division of integers in Java is unlike division in math since any remainder is discarded. In school we learned that 1 / 2 is 0 with a remainder of 1. In Java we just get the 0.
As an aside: To have the remainder, the 1, you may do 1 % 2
or (4 - 3) % 2
. And if we want the result of the division to be 0.5, we need to divide floating point values, for example 1.0 / 2.0
or (4.0 - 3.0) / 2.0
.
Historic perspective: The rules for calculation that I have applied here are by no means unique to Java. The precise rules have been taken over from C++ and C, which may have taken them from even older programming languages. And in practically all programming languages you will find pretty similar rules.
Had you expected left to right evaluation except for the brackets? Another pair of brackets can ensure that:
System.out.println((3 + (4 - 3)) / 2);
Output is:
2
I understood from your question that this was the output you had expected.
It’s becoming hard to read with this many nested brackets, though, so prefer to assign the value to a variable first:
int result = (3 + (4 - 3)) / 2;
System.out.println(result);
Output is still the same, of course. You have probably already realized that the calculation now goes:
(3 + (4 - 3)) / 2 = (3 + 1) / 2
= 4 / 2
= 2
Link: Operator Precedence in Java