Java program of decision making by using the switch case statement
ADVERTISEMENTS
Java program of decision making by using the java switch case statement, In this program you will learn how to make decisions by using a java switch case statement.
- The Java switch case statement is the same as the if..else if...else ladder in which the if..else if...else ladder making a decision among several conditions.
- The Java switch case statement gives easy-to-match conditions & easy readability.
- The Java switch case statement checks faster rather than the if..else if...else ladder.
Syntax of the Java switch case statement
switch (e) {
case constant1:
// statements 1
break;
case constant2:
// statements 2
break;
.
.
.
default:
// default statements
}
The Java switch case statement execution flow
- The C++ switch parameter matches conditions in every case to make a decision.
- There is if any case will be matched with the switch parameter then switch condition checking will be automatically stopped.
- There is if any cases don't match the condition then It navigates to the default case and the switch will be stopped.
Let us understand this statement through a Java example:
// Java program of decision making by using the java switch case statement
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a week number among 1 to 7\n");
int w = in.nextInt();
if (w > 0) {
switch (w) {
case 1:
System.out.println("Hi\nIt's sunday on today, It's the week-off day.\n");
break;
case 2:
System.out.println("Hi\nIt's monday on today, It's the working day.\n");
break;
case 3:
System.out.println("Hi\nIt's tuesday on today, It's the working day.\n");
break;
case 4:
System.out.println("Hi\nIt's wednesday on today, It's the working day.\n");
break;
case 5:
System.out.println("Hi\nIt's thursday on today, It's the working day.\n");
break;
case 6:
System.out.println("Hi\nIt's friday on today, It's the working day.\n");
break;
case 7:
System.out.println("Hi\nIt's saturday on today, It's the week-off day.\n");
break;
// w parameter doesn't match any case constant then It navigates to default:
default:
System.out.println("Sorry, You entered the wrong week number, Kindly try again\n");
}
} else {
System.out.println("Sorry didn't entered any week number!\n");
}
}
}
Output
Enter a week number among 1 to 7
3
Hi
It's tuesday on today, It's the working day.