Skip to main content

JAVA BASICS - HOW TO USE A STRING IN SWITCH STATEMENTS

Simple example to switch statements using string.

Syntax :

switch(String variable)
{
case "" :
case "" :
case "" :
:
:
.
}

Example :

  1. public class StringSwitchDemo
  2. {
  3. public static void main(String[] args)
  4. {
  5.                StringSwitchDemo demo = new StringSwitchDemo();
  6.                String day = "Sunday";
  7.                switch (day)
  8.                {
  9.                               case "Sunday":
  10.                               demo.doSomething();
  11.                               break;
  12.                               case "Monday":
  13.                               demo.doSomethingElse();
  14.                               break;
  15.                               case "Tuesday":
  16.                               case "Wednesday":
  17.                               demo.doSomeOtherThings();
  18.                               break;
  19.                               default:
  20.                               demo.d oDefault();
  21.                               break;   
  22.                }
  23. }
  24.  
  25. private void doSomething() {
  26.      System.out.println("You typed Sunday");
  27. }
  28.  
  29. private void doSomethingElse() {
  30.      System.out.println("You typed Monday");
  31. }
  32.  
  33. private void doSomeOtherThings() {
  34.      System.out.println("StringSwitchDemo.doSomeOtherThings");
  35. }
  36.  
  37. private void doDefault() {
  38.      System.out.println("You typed Wednesday");
  39. }
  40. }


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.