Arithmetical Operations:

  1. Arithmetical operators in Java:


    Arithmetic operators operate on two values of the same type !!!
    The result of the operation has the same type as the operands.

  2. When values of different types are used in an arithmetic operation, the value of the narrow type is converted to wider type


    Example: 2.0 + 3 --> 2.0 + 3.0 = 5.0 (result is double) (int) 2 + (short) 3 --> (int) 2 + (int) 3 = (int 5

  3. Special attention on the division / operator:


    Examples: 7.0 / 4.0 = 1.75 (divide 2 double values, natural) 7 / 4.0 = 1.75 (7 / 4.0 --> 7.0 / 4.0 = 1.75) 7.0 / 4 = 1.75 (7.0 / 4 --> 7.0 / 4.0 = 1.75) 7 / 4 = 1 <- integer division !

    Operator Priority & Associativity

  4. Each operator in Java has:


    Rules to evaluate an expression:

    1. Operators of higher priority is evaluated first
    2. Operators of same priority is evaluated in the associativity direction


  5. Priority & Associativity of Arithmetic Operators:

    Priority Operator(s) Associativity
    1   *   /   % left -> right
    2   +   - left -> right

  6. Same examples:

       6 - 2 * 5
                    ->  6 - (2 * 5)
                    ->  (6 - 10)
                    ->  -4
    
       6 - 2 * 5 - 8 / 3
                    ->  6 - (2 * 5) - (8 / 3)
                    ->  6 - 10 - 2            [Same priority... use assoc rule]
                    ->  (6 - 10) - 2
                    ->  -4 - 2
                    ->  -6
    
       6.0 * (8 / 5)
                    ->  6.0 * (8 / 5)
                    ->  6.0 * 1               [double + int ... convert int !]
                    ->  6.0 * 1.0
                    ->  6.0
    
       6.0 * (8.0 / 5)
                    ->  6.0 * (8.0 / 5)       [double / int ... convert int !]
                    ->  6.0 * (8.0 / 5.0)
                    ->  6.0 * 1.6 
                    ->  9.6
       6.0 * 8 / 5
                    ->  6.0 * 8 / 5           [ same priority... use assoc rule]
                    ->  (6.0 * 8) / 5         [double * int ... convert int !]
                    ->  (6.0 * 8.0) / 5
                    ->  48.0 / 5              [double / int ... convert int !]
                    ->  48.0 / 5.0
                    ->  9.6                   [double value]