Simple example to switch statements using string.
Syntax :
switch(String variable)
{
case "" :
case "" :
case "" :
:
:
.
}
Example :
- public class StringSwitchDemo
- {
- public static void main(String[] args)
- {
- StringSwitchDemo demo = new StringSwitchDemo();
- String day = "Sunday";
- switch (day)
- {
- case "Sunday":
- demo.doSomething();
- break;
- case "Monday":
- demo.doSomethingElse();
- break;
- case "Tuesday":
- case "Wednesday":
- demo.doSomeOtherThings();
- break;
- default:
- demo.d oDefault();
- break;
- }
- }
- private void doSomething() {
- System.out.println("You typed Sunday");
- }
- private void doSomethingElse() {
- System.out.println("You typed Monday");
- }
- private void doSomeOtherThings() {
- System.out.println("StringSwitchDemo.doSomeOtherThings");
- }
- private void doDefault() {
- System.out.println("You typed Wednesday");
- }
- }
Description :
Step 1:Starting of class
Step 3:Start of main function.
Step 5:Object of class is created.
Step 6:String variable "day" is assigned a string value "Sunday".This value can be kept any string and accordingly switch cases must be modified.Here whatever the value of variable "day" is that particular case is executed.
Step 11: Break keyword is used to neglect all the further cases.That is only one case is executed at a time.
Step 25 - Step 38 : These are user defined functions that are called when cases are executed and corresponding message is displayed on the screen.