Java switch Statement
In this chapter you will learn:
- What is the Java Switch Statement
- Syntax for Java switch Statement
- Example - Java Switch Statement
- Example - How to use the optional break statement
- Example - How to write nested switch Statements
Description
The switch
statement is a multiway branch statement.
It provides a better alternative than a large series of if-else-if
statements.
Syntax
Here is the general form of a switch
statement:
switch (expression) {
case value1: /*from w w w . j ava2 s.co m*/
statement sequence
break;
case value2:
statement sequence
break;
.
.
.
case valueN:
statement sequence
break;
default:
default statement sequence
}
The value1
to valueN
are the possible
case values for expression
.
Duplicate case values are not allowed.
A break
statement jumps out of switch statement
to the first line that follows the entire switch
statement.
Example
Here is a simple example that uses a switch
statement:
public class Main {
public static void main(String args[]) {
for (int i = 0; i < 6; i++)
switch (i) {
case 0://from w ww.ja va 2 s. c o m
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;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
The output produced by this program is shown here:
Example 2
The break statement is optional.
If you omit the break
, execution will continue on into the next case.
For example, consider the following program:
public class Main {
public static void main(String args[]) {
for (int i = 0; i < 12; i++)
switch (i) {
case 0:/*ww w .j a v a2 s. c om*/
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
This program generates the following output:
Example 3
Java supports the nested switch
statements.
For example, the following fragment is a valid nested switch
statement.
public class Main {
public static void main(String args[]) {
for (int i = 0; i < 6; i++)
switch(i) {
case 0: //from w w w. j av a 2s . com
switch(i+1) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1:
System.out.println("target is one");
break;
}
break;
case 2: // ...
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- What is Java for loop
- How to write for loop
- Example - A simple for loop
- Example - loops reversively
- Example - Calculate the prime number with for loop
- Example - How to use comma in the for loop statement
- How to write different forms of for loop
- How to write nested for loops