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 - while Statement

Syntax (JLS §14.11)

    while( boolean expression ) {
        statement(s);
    }

  • executes statement(s) repeatedly until the value of expression is false
  • if the expression is false the first time, the statements will never execute
    int i = 1;
    
    while( i>3 ) {
        System.out.println("This shouldn't print");
    }

  • both the break and continue statements can be used to alter the processing of a while loop
    while( i < 10 ){
        if( i == 5 ) break;     // break out of loop
        System.out.println(i);
        i++;
    }

    while( i < 10 ){
        if( i==5 ) { 
           i++;
           continue;   // force next loop
        }
        
        System.out.println(i);
        i++;
    }

Example Code

Traps

  • non-boolean expression
  • using '=' instead of '==' for boolean expression

Statements if switch for while do
Labels Exceptions Handling Exceptions try-catch-finally