Operator Precedence in Java

It's possible to combine multiple arithmetic expressions in one statement. For instance the following line adds the numbers one through five:

`int m = 1 + 2 + 3 + 4 + 5;`

A slightly more interesting example: the following program calculates the energy equivalent of an electron using Einstein's famous formula E = mc2.

``````class mc2 {
public static void main (String args[]) {

double mass = 9.1096E-25;
double c = 2.998E8;
double E = mass * c * c;
System.out.println(E);
}
}``````

Here's the output:

```\$ javac mc2.java
\$ java mc2
8.18771e-08
```

This is all very obvious. However if you use different operators on the same line it's not always clear what the result will be. For instance consider the following code fragment:

``````int n = 1 - 2 * 3 - 4 + 5;
``````

Is n equal to -2? You might think so if you just calculate from left to right. However if you compile this in a program and print out the result you'll find that Java thinks n is equal to -4. Java got that number because it performs all multiplications before it performs any additions or subtractions. If you like you can think of the calculation Java did as being:

``````int n = 1 - (2 * 3) - 4 + 5;
``````

This is an issue of order of evaluation. Within the limited number of operators you've learned so far here is how Java calculates:

1. *, /, % Do all multiplications, divisions and remainders from left to right.
2. +, - Do additions and subtractions from left to right.
3. = Assign the right-hand side to the left-hand side

Copyright 1997, 2005 Elliotte Rusty Harold
elharo@metalab.unc.edu