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

Flow Control and Exception Handling - if...else Statement

Syntax

    if( boolean expression ) {
        statement1;
        ...
        statementn;
    }    
        
    if( boolean expression ) {
        statement1;
        ....
        statementn;
    } else {
        statementa;
        ...
        statementz;
    }    
  • the expression must be a boolean type
  • curly braces are only required if there is more than one execution statement
  • in the first form, the statements are only executed if the boolean expression evaluates to true
  • in the second form, the first set of statements are executed if the boolean expression evaluates to true; otherwise, the statements following else are executed
  • may be nested
    if( x == y ) {
      // do this
    } else if( x > y ) {        // nested 'if'
      // do this
    } else {
      // do this
    }    

Example Code

Traps

  • a non-boolean value used in the if( )
  • using the assignment operator '=' vs '=='
Statements if switch for while do
Labels Exceptions Handling Exceptions try-catch-finally