Arithmetic Operator Precedence, Beginner



























1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Fundamental > Arithmetic & Boolean Operators > Operator Precedence >
 *      ArithmeticOperatorPrecedence.java
 *
 * Shows the relative precedence of the arithmetic operators (+, -, /, %).  The
 * order of precedence, from highest to lowest, is:
 * 
 *      -, +        (unary, as in -1 to denote a negative 1)
 *      *, /, %
 *      +, -
 * @author  Feihong Hsu
 */

public class ArithmeticOperatorPrecedence {

	public static void main(String[] args) {
        // Unary - and unary + are evaluated before *, /, %:
        int ans1 = -4 * -23 / -42 % +78;
        int ans2 = (-4) * (-23) / (-42) % (+78);
        System.out.println( ans1 == ans2 );
        
        // The *, /, and % operators are evaluated before + and -:
        double ans3 = 2.3 - 1.2 * 33 + 7.0 / 98 - 1.2 % 5.5;
        double ans4 = 2.3 - (1.2 * 33) + (7.0 / 98) - (1.2 % 5.5);
        System.out.println( ans3 == ans4 );
	}
}

Explanation