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 - Precedence

Operator precdence (JPL pg 378)
Operator type Operators
Postfix [] . (params) expr++ expr--
Unary ++expr --expr +expr -expr ~ !
Creation or Cast new (type)expr
Multiplicative * / %
Additive + -
Shift << >> >>>
Relational < > >= <= instanceof
Equality == !=
Bitwise AND &
Bitwise exclusive OR ^
Bitwise inclusive OR |
Logical AND &&
Logical OR ||
Ternary ?:
Assignment = += -= *= /= %= >>= <<= >>>= &= ^= |=
  • Precedence can be overridden using parantheses
     5 + 3  * 2               // Result: 11
    (5 + 3) * 2               // Result: 16
  • when two operators of the same precedence are next to each other, associativity rules apply
  • all binary operators (except assignment operators) are left-associative
  • assignment is right-associative
    a - b + c is evaluated as (a - b) + c 
    5 - 2 + 1    // Result: 4, not 2
    
    
    a = b = c is evaluated as  a = (b = c) 
    
    int a;
    int b = 5;
    int c = 1;
    
    a = b = c;              // Result: 1

Possible problem areas

  • where boolean expressions are used to control loops
    while( v = stream.next() != null )
        processValue(v);
    
    according to precedence rules, evaluates as    
        v = (stream.next() != null )
        
    not the intended    
        (v = stream.next()) != null

Example Code



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