How do I use the continue statement?

The continue statement has two forms, the unlabeled and labeled continue statement. The first example shows you how to use the unlabeled continue statement while the second example shows you how to use the labeled continue statement.

package org.kodejava.example.lang;

public class ContinueDemo {
    public static void main(String[] args) {
        int[] numbers = {5, 11, 3, 9, 12, 15, 4, 7, 6, 17};
        int length = numbers.length;
        int counter = 0;

        for (int number : numbers) {
            // When number is greater or equals to 10 skip the
            // current loop and continue to the next loop because
            // we only interested to count number less than 10.
            if (number >= 10) {
                continue;
            }

            counter++;
        }

        System.out.println("Found " + counter + " numbers less than 10.");

        // The example below used a labeled continue statement. In the
        // loop below we sum the number in the array until reminder of
        // the number divided by 2 equals to zero. If the reminder is
        // zero we skip to the next dimension of the array.
        int[][] data = {
                {8, 2, 1},
                {3, 3},
                {3, 4, 5},
                {5, 4},
                {6, 5, 2}};
        int total = 0;

        outer:
        for (int[] aData : data) {
            for (int j = 0; j < aData.length; j++) {
                if (aData[j] % 2 == 0) {
                    continue outer;
                }

                total += aData[j];
            }
        }

        System.out.println("Total = " + total);
    }
}

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.example.lang;

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 use to iterate over a range of values. For instance if you want to iterate from zero 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.example.lang;

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-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.example.lang;

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 executes while the countDown value is bigger or equals to zero.

package org.kodejava.example.lang;

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 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.example.lang;

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

How do I use the if-then-else statement?

The if-then-else control flow statement adds a secondary path to the if statement when the expression evaluates to false. When it evaluates to false the else block will be executed.

Below is the program that takes input of user test score and evaluates the score to get the corresponding grade.

package org.kodejava.example.lang;

import java.io.Console;

public class IfThenElseDemo {
    public static void main(String[] args) {
        // Get an instance of system console for taking user
        // input.
        Console c = System.console();

        int score = 0;
        String grade;

        System.out.print("Please enter your score: ");

        try {
            // Take user score input and convert the input
            // value into number.
            score = Integer.valueOf(c.readLine());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 60) {
            grade = "C";
        } else if (score >= 50) {
            grade = "D";
        } else {
            grade = "F";
        }

        System.out.println("Grade = " + grade);
    }
}

When the program executed you’ll need to input the test score and the program will give you the grade.

Please enter your score: 75
Grade = C

How do I use the if-then statement?

The if-then is the most basic control flow statement. It will execute the block of statement only if the test expression evaluated equals to true. Let’s see the example below:

package org.kodejava.example.lang;

public class IfThenDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        // If the evaluation of a > b is true than the if block is
        // executed. In the block below we just print that the value
        // of a is bigger than b.
        if (a > b) {
            System.out.println("A(" + a + ") is bigger than B(" + b + ")");
        }

        // When we have only a single command inside a block we can
        // remove the opening and closing braces for the block ({..}).
        // But it is a good practice to always enclose the block with
        // braces.
        if (b < a)
            System.out.println("B(" + b + ") is smaller that A(" + a + ")");
    }
}

The result of the above program is:

A(10) is bigger than B(5)
B(5) is smaller that A(10)