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 in and running it quickly anyway.

If you carefully read the preceding rules on operator precedence, you probably have fallen asleep by now. In the event that you managed to remain awake, you will know that the result is 13. Here's why:

4 - 2 is 2. Hang on to 2.

9 / 3 is 3

3 * 2 is 6

10 + 6 is 16

16 - 5 is 11

11 + 2 is 13

Straightforward enough.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net