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 - Overflow and Underflow

  • an overflow results when a calculated value is larger than the number of bytes allowed for its type
  • a underflow results when a calculated value is smaller than the number of bytes assigned to its type
  • Java handles overflows by discarding the high-order-bytes that won't fit into the number of bytes allowed by its type (JJ pg 52)
 int n = 2000000000;
 System.out.println(n * n); // output: -1651507200
 
An int is 32-bits, the result of n*n is 
4,000,000,000,000,000,000 which
needs 64-bits which in binary is:

    ---------- high-order bytes ------- 
    00110111 10000010 11011010 11001110

    ------- low order bytes -----------
    10011101 10010000 00000000 00000000

because an 32-bit cannot retain the number, 
the 4 high-order bytes are
dropped leaving the four low-order bytes:

    10011101 10010000 00000000 00000000
                                    
which represent 1651507200 and since the right most bit
is a 1 the sign value is negative

  • overflow or underflow conditions never throw a runtime exception; instead the sign of the result may not be the same as that expected in the mathematical result

You probably won't need to calculate overflows or underflows on the exam but should understand how they work.

(also see Working with Hex, Octal and Binary numbers)

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