-3

Why System.out.println(3+(4-3)/2); is printing 3 but not 2 in java but System.out.println(4/2) is printing 2 correctly.

    public class Sum {

        public static void main(String[] args) {
            System.out.println(3 + (4 - 3) / 2);
        }
    }
Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
  • 6
    To me, it looks more like OP is struggling with operator order and is surprised that the / is evaluated before the +. –  Jul 23 '20 at 19:54
  • It's because `(4 - 3) / 2 = 1 / 2 = 0` – Arvind Kumar Avinash Jul 23 '20 at 20:01
  • Probably related but probably more advanced: [What is the right precedence of the math expression](https://stackoverflow.com/questions/4023673/what-is-the-right-precedence-of-the-math-expression) – Ole V.V. Jul 23 '20 at 20:01

1 Answers1

2

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

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117