Flow Control

by Michael Thomas

(Tutorial Home Page)

(not completed)

Resources

Topic Notes
if Rules:
  • Must take a boolean expression.
  • You must block the code with "{}" unless there is only one line of code.
if - Examples
  • Example of basic if statement:
    if ( boolean )
       System.out.println("True"); //If true do this
    else if
    {  System.out.println("False"); //If false do this
       System.out.println("Code blocks for 2 or more");
    }
switch Rules:
  • The argument to a switch statement must be a byte, short, int, or char.  Compile error if boolean, long, float, or double.
  • The "default:" switch logically should be placed last, however it may be located anywhere.  (see Ex-B )
  • Once you have entered a case, you will continue to enter the subsequent cases until you encounter a "break;" statement.  (see Ex-B)
  • Braces "{}" start and stop the switch statement.  Do not use braces "{}" to group the statements between the case statements.
switch - Examples Examples:
  • A.  Standard switch statement using an int:
    int myInt = 1;
    switch ( myInt )
    { case 1:
         myInt = 100; break;
      case 2:
         myInt = 200;  break;
      default:
         myInt = 0;
    }
  • B.  Example of using the "break;" statement.
    char myChar = 'B';
    switch ( myChar )
    {     
      case 'A':
          System.out.print("A,");
      case 'B':
          System.out.print("B,");
      case 'C':
          System.out.print("C,");
          break;
      case 'D':
          System.out.print("D,");
          break;
      default:
          System.out.println("Default,");
          break;
    }
    Note:  Output = "B, C,"
for Rules:
  • need to complete....

Syntax:

for (initialization; termination; increment) {
  statement(s)
}
 

Example:

for(int i=1; i<11; i++){
  System.out.println("Count is: " + i);
}


 

while Rules:
  • Must take a boolean expression.  
  • Enters express if boolean expression is true.  Continues to loop until boolean expression is false.
  • You must block the code with "{}" unless there is only one line of code.
  • break - breaks out of the loop.

Examples:

  • Example A. 
    x = 0;
    while ( x < 10 ) {
      x++;
    }
  • Example B.
    blnContinue = true;
    x = 0;
    while ( blnContinue ) {
      x++;
      if ( x == 5 ) blnContinue = false;
    }
  • Example C. (using break)
    x = 0;
    while ( true ) {
      x++;
      if ( x == 5 ) break;
    }
do {} while Rules:
  • Must take a boolean expression.  
  • Always enters the do loop the first time.  Continues to loop until boolean expression is false.
  • You must block the code with "{}" unless there is only one line of code.
  • break - breaks out of the loop.

Examples:

  • Example A:
    x = 0;
    do {
      x++;
    } while ( x < 10 );
  • Example B: (using break)
    x = 0;
    do {
      x++;
      if ( x < 10 ) break;
    } while ( true );
labels  
break  
continue  
( ? : )