Switch, do while, For Each, Continue Statement in Java


Switch statement

The switch statement is Java's multi-way branch statement. It is used to take the place of long if-else if-else chains, and make them more readable. However, unlike if statements, one may not use inequalities; each value must be concretely defined.

There are three critical components to the switch statement:

  • case : This is the value that is evaluated for equivalence with the argument to the switch statement.
  • default : This is an optional, catch-all expression, should none of the case statements evaluate to true.
  • Abrupt completion of the case statement; usually break: This is required to prevent the undesired evaluation of further case statements.

With the exception of continue, it is possible to use any statement which would cause the abrupt completion of a statement. This includes:

  • break
  • return
  • throw

In the example below, a typical switch statement is written with four possible cases, including default.

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
switch (i) {
	case 0:
		System.out.println("i is zero");
		break;
	case 1:
		System.out.println("i is one");
		break;
	case 2:
		System.out.println("i is two");
		break;
	default:
		System.out.println("i is less than zero or greater than two");
}

By omitting break or any statement which would an abrupt completion, we can leverage what are known as "fall-through" cases, which evaluate against several values. This can be used to create ranges for a value to be successful against, but is still not as flexible as inequalities.

Scanner scan = new Scanner(System.in);
int foo = scan.nextInt();
switch(foo) {
	case 1:
		System.out.println("I'm equal or greater than one");
	case 2:
	case 3: 
		System.out.println("I'm one, two, or three");
		break;
	default:
		System.out.println("I'm not either one, two, or three");
}

In case of foo == 1 the output will be:

I'm equal or greater than one
I'm one, two, or three

In case of foo == 3 the output will be:

I'm one, two, or three
//Version ≥ Java SE 5

The switch statement can also be used with enums.

enum Option {
	BLUE_PILL,
	RED_PILL
}
 
public void takeOne(Option option) {
	switch(option) {
		case BLUE_PILL:
			System.out.println("Story ends, wake up, believe whatever you want.");
			break;
		case RED_PILL:
			System.out.println("I show you how deep the rabbit hole goes.");
			break;
	}
}
//Version ≥ Java SE 7

The switch statement can also be used with Strings.

public void rhymingGame(String phrase) {
	switch (phrase) {
		case "apples and pears":
			System.out.println("Stairs");
			break;
		case "lorry":
			System.out.println("truck");
			break;
		default:
			System.out.println("Don't know any more");
	}
}

do...while Loop

The do...while loop differs from other loops in that it is guaranteed to execute at least once. It is also called the "post-test loop" structure because the conditional statement is performed after the main loop body.

int i = 0;
do {
	i++;
	System.out.println(i);
} while (i < 100); // Condition gets checked AFTER the content of the loop executes.

In this example, the loop will run until the number 100 is printed (even though the condition is i < 100 and not i <= 100), because the loop condition is evaluated after the loop executes.

With the guarantee of at least one execution, it is possible to declare variables outside of the loop and initialize them inside.

String theWord;
Scanner scan = new Scanner(System.in);
do {
	theWord = scan.nextLine();
} while (!theWord.equals("Bird"));
 
System.out.println(theWord);

In this context, theWord is defined outside of the loop, but since it's guaranteed to have a value based on its natural flow, theWord will be initialized.


For Each

//Version ≥ Java SE 5

With Java 5 and up, one can use for-each loops, also known as enhanced for-loops:

List strings = new ArrayList();
 
strings.add("This");
strings.add("is");
strings.add("a for-each loop");

(String string : strings) { System.out.println(string); }

For each loops can be used to iterate over Arrays and implementations of the Iterable interface, the later includes Collections classes, such as List or Set.

The loop variable can be of any type that is assignable from the source type.

The loop variable for a enhanced for loop for Iterable or T[] can be of type S, if

  • T extends S
  • both T and S are primitive types and assignable without a cast
  • S is a primitive type and T can be converted to a type assignable to S after unboxing conversion.
  • T is a primitive type and can be converted to S by autoboxing conversion.

Examples:

T elements = ...
     for (S s : elements) {
}
T S Compiles
int[] long yes
long[] int no
Iterable<Byte> long yes
Iterable<String> CharSequence yes
Iterable<CharSequence> String no
int[] Long no
int[] Integer yes

Continue Statement in Java

The continue statement is used to skip the remaining steps in the current iteration and start with the next loop iteration. The control goes from the continue statement to the step value (increment or decrement), if any.

String[] programmers = {"Adrian", "Paul", "John", "Harry"};
 
//john is not printed out
for (String name : programmers) {
	if (name.equals("John"))
		continue;
	System.out.println(name);
}

The continue statement can also make the control of the program shift to the step value (if any) of a named loop:

Outer: // The name of the outermost loop is kept here as 'Outer'
for(int i = 0; i < 5; )
{
	for(int j = 0; j < 5; j++)
	{
		continue Outer;
	}
}

Basic Programs