Java - The switch construct in Java

Switch is the control statement in java which also turns the normal flow
control of the program as per conditions. It works same as If-Else
construct. This is the difference between Switch
and If-Else construct that switch is used
for reduce the if statements. If the multiple choices are available then we
generally use the If-Else construct otherwise Switch
is easier than the If-Else construct. Switch checks
your choice and jump on that case label if the case
exists otherwise control is sent to the default label.
In this Program you will see that how to use the switch
statement. This program take a number and check weather the number lies between
1 to 7. If user enters the number between 1 to 7 then program print the name of
the day in sequence like for 1 prints Sunday, for 2 prints Monday and so on
otherwise prints the message Invalid entry!. If
user enters any character then the message will be printed by catch
block. This program also using the break statement. The normal flow of control
quits from the Switch block whenever break statement occurs. Full running
program code is provided with the example.
Here is a code of program:-
import java.io.*;
public class Switch{
public static void main(String args[]) throws Exception{
int ch;
System.out.println("Enter 1 for Sunday.");
System.out.println("Enter 2 for Monday.");
System.out.println("Enter 3 for Tuesday.");
System.out.println("Enter 4 for Wednesday.");
System.out.println("Enter 5 for Thrusday.");
System.out.println("Enter 6 for Friday.");
System.out.println("Enter 7 for Saturday.");
System.out.print("your choice is : ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try{
ch=Integer.parseInt(in.readLine());
switch(ch){
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("Thrusday");
break;
case 6: System.out.println("Friday");
break;
case 7: System.out.println("Saturday");
break;
default: System.out.println("Invalid entry!");
break;
}
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage() + " is not a numeric value.");
System.exit(0);
}
}
}
|
Download The Switch Example

|