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:-
We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.
Posted on: June 8, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles