Google
 

 

up previous next contents
Up: 2. Day 2: The Previous: 2.6 Comments and Javadoc Next: 2.8 Classes and objects   Contents

Subsections

2.7 Flow control and loops

2.7.1 Introduction

A program consisting of only consecutive statements is immediately useful, but very limited. The ability to control the order in which statements are executed adds enormous value to any program. This lesson covers all the control flow statements that direct the order of execution, except for exceptions.

2.7.2 Objectives

Upon completion of this section, students will be able to:

  • Define expression statements and declaration statements.
  • Describe the operation of Java's control-flow statements.
  • Use Java's if-else, switch, while, do-while, and for statements.
  • Use labels, and labeled break and continue statements.

2.7.3 Statements and blocks

  • Two basic statements - expression statements, declaration statements.
  • Expression statements - such as i++ -have a semi-colon at the end.

2.7.3.1 Expressions that can be made into statements

  • Assignment: those that contain =
  • Prefix or postfix forms of ++ and -
  • Methods calls.
  • Object creation statements (new operator).

2.7.3.2 Declaration statements

  • Declare a variable and initialize it to a value.
  • Can appear anywhere inside a block.
  • Local variables exist only as long as the block containing their code is executing.
  • Braces group zero or more statements into a block.

2.7.4 if-else

  • Basic form of conditional control flow.
      if (boolean-expression)
         statement1
      else
         statement2
    
  • Example
      class IfElse1 {
         public static void main (String[] args) {
         int i = 10;
         if ( i==1 )
            System.out.println( "i == 1" );
         else if ( i==2 )
            System.out.println( "i == 2" );
         else if ( i==3 )
            System.out.println( "i == 3" );
         else
            System.out.println( "don't know what 'i' is" );
         }
      }
    

2.7.5 switch

  • Evaluates an integer expression in the switch statement.
  • Transfers control to an appropriate case label.
  • If no match is found, control is transferred to a default label.
  • If there is no default label and no other match is found, the switch statement is skipped.
  • A break statement is usually used at the end of each case. If a break is not used, control flow falls through to the next case.
  • All case labels must be constant expressions.
  • The value that you are switching on must be byte, short, char, or int.
  • Example:
      switch (verbosity)
      {
         case BLATHERING:
            System.out.println("blah blah blah ... my name is ...");
         case NORMAL:
            System.out.println("What is your name?");
         case TERSE:
            System.out.println("Yo.");
            break;
         default:
            System.out.println("Hello.");
      }
    

2.7.6 while and do-while

  • A while loop is executed repeatedly until its boolean expression evaluates to false.
  • A while loop will execute zero or more times.
  • The boolean-expression can be any expression that returns a boolean value.
      while (boolean-expression)
         statement
    

  • A do-while loop executes at least once:
      do 
         statement
      while (boolean-expression)
    

2.7.7 for

  • Used to loop over a range of values from beginning to end.
        for (init-expr; boolean-expr; incr-expr)
           statement
    
  • Typically used to iterate a variable over a range of values.
        char ch[] = new char[s.length()];
        for (int i=0; i<s.length(); i++)
        {
           ch[i] = s.charAt(i);
        }
    

2.7.8 Labels

  • Statements can be labeled.
  • Typically used on blocks and loops.
      label : statement
    

2.7.9 break

  • Used to exit from any block (not just a switch).
  • Most often used to break out of a loop.
  • An unlabeled break terminates the innermost switch, for, while, or do-while.
  • To terminate an outer statement, label the outer statement and use its label name in the break statement.

2.7.10 continue

  • Skips to the end of a loop's body and evaluates the boolean expression that controls the loop.
  • Has meaning only inside loops: while, do-while, and for.
  • A labeled continue will break out of any inner loops on its way to the next iteration of the named loop.

2.7.11 return

  • Terminates execution of a method and returns to the invoker.
  • If the method has a return type, the return must include an expression of a type that could be assigned to the return type.
        public static double absolute (double val)
        {
           if ( val<0 )
              return -val;
           else
              return val;
        }
    

2.7.12 No goto Statement

  • No goto construct to transfer control to an arbitrary statement in a method.
  • Primary uses of goto in other languages:
    • Controlling outer loops from within nested loops. Java provides labeled break and continue.
    • Skipping the rest of a block of code that is not in a loop when an answer or error is found. Use a labeled break.
    • Executing cleanup code before a method or block of code exits. Use a labeled break, or the finally construct of the try statement.