Java Programming/Flow control

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Navigation Left Arrow.svg Classes, Objects and Types Java Programming
Flow control
Flow control Navigation Right Arrow.svg


Navigate Language Fundamentals topic: ( v d e )

Contents

[edit] If statements

The if statement is a section of code that only executes if a condition is true. It may also be paired with else to indicate a section of code that may be executed instead.

if (a == 5)
{
    System.out.println ("a equals 5");
} else {
    System.out.println ("a is not 5");
}

[edit] While statements

The while statement executes a block of code as long as a condition is true.

  while (!done)
  {
    /* ... */
    {
      done = true;
    }
  }

[edit] Do ... while statements

The do while statement will execute a block of code at least once, and continue execution as long as the condition is true.

  do {
    /* ... */
  } while (!done);

[edit] For loops

The for loop provides addtional flow control over a while statement. In addition to executing code as long as a condition is true, it provides sections to execute code before the loop starts, and code that executes tat the end of each loop.

  for (int i=0; i<10; ++i)
  {
    /* ... */
  }

[edit] Boolean logic

  •  ! : Boolean not
  • && : Boolean and
  • || : Boolean or.

The && and || operators should not be confused with & and | which are bitwise operators rather than boolean operators.

[edit] Switch statements

The switch statement evaluates an integer (or enumeration), and based on the value provided, jumps to a specific case lavel within the switch block.

  switch(i)
  {
    case 1: 
      System.out.println("i = 1");
      break;
    case 2: 
      System.out.println("i = 2");
      break;
    default: 
      System.out.println("i is some other value");
      break;
  }

[edit] Break and continue keywords

The break keyword exits a flow control loop. The continue keyword jumps to the end of the loop just before the condition is checked.

These two statements can be combined with a label to break out of multiple layers of loops.

[edit] Try ... catch statements

The try-catch statements are used to catch any exceptions or other throwable objects within the code.

  try {
     /* ... */
  } catch (Exception e) { 
     /* Handle exception here... */
  }

These statements can also appear with a finally block, which executes whenever the try block finishes or an unhandled exception is thrown. The execution of the finally block can be bypassed by the System.exit() function, or by terminating the virtual machine without the chance for it to execute further code.