O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Operator Precedence

The compiler will follow certain rules when determining how to execute a mathematical statement containing multiple operators.

Lucky for us, they are the standard rules regarding operator precedence:

  1. Operators inside parentheses are evaluated first.

  2. Multiplication and division (left to right).

  3. Addition and subtraction (left to right).

The following code illustrates these concepts.

OpPrecedence.java

public class OpPrecedence {
   public static void main(String[] args) {
      short x = 10 + 9 / 3 * 2 - 5 + (4 - 2);
      System.out.println(x);
   }
}

That code is a complete class that you can type in, compile, and run. I know we haven't talked about classes yet, but I'm going to try to do that a lot so you can get comfortable typing the code ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required