Switch Case in java with Examples

The Switch statement tests the value of a given expression against a list of case labels, when they get matches, block of statement associated with that case in executed.

The general form of switch case

Syntax:-

switch (expression)
{
case label1:
block of statement
break;

case label2:
block of statement
break;

case label3:
block of statement
break;
.
.
.

case labeln:
block of statement
break;

default:
block of statement
break;
}

Note :-

# The Expression and label are integer or characters.
# floats are not allowing in case labels.
# labels much be unique.
# Block of statement may be zero or more than one statements.
# Case labels end with colon(:).
# The break is followed by semicolon(;).
# Default case is optional case.
# break is optional, if 2 or more case labels belongs to same statement.

How Case Statement Execute

The expression is made to compared with each case labels, if they matches each others than block of statements related to particular case is executed and than control is transferred to statement that following the switch case.

The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement that following the switch case.

If value of expression is does not match with case label than default statement is execute and than control is transferred to statement that following the switch case.

Examples

Program to accept day number of week and display the corresponding week day

import java.util.Scanner;
class group{
public static void main(String arg[]){
int day;
Scanner week = new Scanner(System.in);
System.out.println("Enter day number of the week ");
day = week.nextInt();
switch(day){
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
}
}
}

Example:-
Example for Default case is optional and 2 more case labels belongs to same statement.

import java.util.Scanner;

class group{
public static void main(String angt[]){
Scanner data = new Scanner(System.in);
int num;
System.out.println("Enter a number below 10");
num=data.nextInt();

switch(num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("The number is between 0 and 6");
break;
case 6:
case 7:
case 8:
case 9:
System.out.println("The number is between 5 and 10");
break;

}
}
}


Previous Code:-
else if statement

List Code:-
Java codes

Next Code:-
for loop

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top