How do I use the break statement?

The break statement has two forms, the unlabeled and labeled break. On the example below you see the first example as the unlabeled break. This type of break statement will terminate the innermost loop such as the for, while and do-while loop.

On the second example you’ll see the labeled break. We have two loops, the infinite while and the inner for loop. Using the labeled break we can terminate the outermost loop. In the for loop when the value of y equals to 5 then it will break to the start: label which will continue the program execution to the line after the while loop.

package org.kodejava.basic;

public class BreakDemo {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 6, 9, 8, 7, 4, 2, 1, 10};

        int index;
        boolean found = false;

        int search = 7;
        for (index = 0; index < numbers.length; index++) {
            if (numbers[index] == search) {
                found = true;
                break;
            }
        }

        if (found) {
            System.out.println(search + " found at index " + index);
        } else {
            System.out.println(search + " was not found.");
        }

        start:
        while (true) {
            for (int y = 0; y < 10; y++) {
                System.out.print("y = " + y + "; ");
                if (y == 5) {
                    System.out.println();
                    break start;
                }
            }
        }
    }
}

How do I use the for loop statement?

The for loop can be used to iterate over a range of values. For instance if you want to iterate from 0 to 10 or if you want to iterate through all the items of an array. Below you’ll see two forms of a for loop. The first one is the general form of a for loop and the second one is an enhanced for loop that also known as the for..each loop.

The general form of for loop consists of three parts:

for (initialization; termination; increment) {
    ....
}
  • The initialization: it initializes the loop, it executed once at the beginning of the loop.
  • The termination: the loop executes as long as the termination evaluates to true.
  • The increment: it executed at the end of every loop, the expression can be either an increment or decrement.
package org.kodejava.basic;

public class ForDemo {
    public static void main(String[] args) {
        // Do a loop from 0 to 10.
        for (int i = 0; i <= 10; i++) {
            System.out.println("i = " + i);
        }

        // Loop through all the array items.
        int[] numbers = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int number : numbers) {
            System.out.println("number = " + number);
        }
    }
}

The result of the program is:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
number = 0
number = 1
number = 2
number = 3
number = 4
number = 5
number = 6
number = 7
number = 8
number = 9
number = 10

How do I use the do-while loop statement?

There is also a do-while loop in the Java programming language. Instead of evaluating the expression at the beginning like the while loop does the do-while loop evaluates its expression at the end of the loop. Due to this the loop executes at least once during the program execution.

package org.kodejava.basic;

public class DoWhileDemo {
    public static void main(String[] args) {
        int i = 0;

        // The do-while statement executes at least once because
        // the expression is checked at the end of the loop
        // process.
        do {
            // This block will be executed while `i` is smaller or
            // equals to 10.
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}

The program prints the following result:

0
1
2
3
4
5
6
7
8
9
10

How do I use the while loop statement?

The code below demonstrate how to use the while loop statement. The while statement will check if its expression evaluates to true and execute the while statement block.

The program below will execute while the countDown value is bigger or equals to zero.

package org.kodejava.basic;

public class WhileDemo {
    public static void main(String[] args) {
        // Start the count-down from 10
        int countDown = 10;

        // Do the count-down process while the value of
        // countDown is bigger or equals to zero.
        while (countDown >= 0) {
            System.out.println(countDown);
            countDown--;

            try {
                // Adds one-second delay.
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

How do I use the switch statement?

The program below demonstrate how to use the switch statement. The switch statement can work with the byte, short, int and char primitive data types and the corresponding wrappers of these data type such as Byte, Short, Integer and Character. It also work with enumerated types, refer to the following example: How do I use enum in switch statement?.

The switch block or the body can contains one or more case or default labels. The switch statement evaluates its expression and evaluate the appropriate case.

You’ll also notice that after each case labels we have a break statement. This break statement causes the program execution to continue outside the switch block. Without using a break the case will fall-through to another case or default label.

package org.kodejava.basic;

import java.util.Scanner;

public class SwitchDemo {
    public static void main(String[] args) {
        System.out.println("The Planets");
        System.out.println("===================================");
        System.out.println("1. Mercury");
        System.out.println("2. Venus");
        System.out.println("3. Earth");
        System.out.println("4. Mars");
        System.out.println("5. Jupiter");
        System.out.println("6. Saturn");
        System.out.println("7. Uranus");
        System.out.println("8. Neptune");
        System.out.println();
        System.out.print("Please choose your favorite destination: ");

        Scanner scanner = new Scanner(System.in);
        int destination = scanner.nextInt();

        System.out.print("Welcome to ");
        switch (destination) {
            case 1:
                System.out.println("Mercury");
                break;
            case 2:
                System.out.println("Venus");
                break;
            case 3:
                System.out.println("Earth");
                break;
            case 4:
                System.out.println("Mars");
                break;
            case 5:
                System.out.println("Jupiter");
                break;
            case 6:
                System.out.println("Saturn");
                break;
            case 7:
                System.out.println("Uranus");
                break;
            case 8:
                System.out.println("Neptune");
                break;
            default:
                System.out.println("Invalid Destination");
        }
    }
}

When you run the program you’ll have to following on the screen:

The Planets
===================================
1. Mercury
2. Venus
3. Earth
4. Mars
5. Jupiter
6. Saturn
7. Uranus
8. Neptune

Please choose your favorite destination: 3
Welcome to Earth