Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Operators and Assignments - Arithmetic Operators

Additive operators (JLS §15.18)

  • + and -
  • have the same precedence and are left-associative
  • operands must be primitive numeric types (see exception for String and +) or compile error occurs

Multiplicative operators (JLS §15.17)

  • *, /, %
  • have the same precedence and are left-associative
  • operands must be primitive numeric types or compile error occurs;

Integer Division and Division by Zero (JJ pg 50, JLS §15.17.2)

  • integer division rounds towards 0; ie result is truncated
        10 / 3 = 3;     // truncated result 
    
  • if the value of the divisor in integer division is 0 an ArithmeticException is thrown
        10 / 0          // runtime error: ArithmeticException
    
  • if the value of the divisor in floating-point division is 0 no exception is thrown; the value of the results are as follows:
    • division of a positive floating-point value: POSITIVE_INFINITY
    • division of a negative floating-point value: NEGATIVE_INFINITY
    • division of a floating-point value by -0: POSITIVE_INFINITY
    10.34 /  0           // result:  Infinity
   -10.34 /  0           // result: -Infinity    
    10.34 / -0           // result:  Infinity
     0    /  0           // result:  NaN (Not a number) 

Modulo operations (JLS §15.17.3)

  • the modulo operator % is also called the remainder operator as it returns the remainder, or fractional part, of a division operation
  • x % y is equivalent to x - ((int) (x/y) * y)
  • can be used with both integer and floating-point numbers
  • following rules apply as to the sign of the result:
    • result is negative if the divdend is negative
    • result is positive if the divdend is positive
    • if the divisor is zero, a runtime ArithmeticException is thrown
    • if the dividend is a floating-point value and the divisor is zero, no exception is thrown and the result is NaN
      5 % 3  =  2
     -5 % 3  = -2
    5.0 % 3  =  2.0
   -5.0 % 3  = -2.0 
    5.0 % 0  = NaN              // not a number

Also see:

Example Code

Traps

  • floating point operation throwing an ArithmeticException


Conversions Promotion Overflow Unary Prefix Arithmetic
  Bin/Hex/Octal Bitwise Shift Comparison Logical Assignment
  Cast Ternary String equals() Precedence Bit vs Logic
  Method Invocation