Java Program to Implement switch statement on strings


In this article, we will understand how to implement switch statement on strings. The switch expression is evaluated once. The value of the expression is compared with the values of each case. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

Input string: Java

The desired output would be

Using siwtch cases:
We shall use Java for our coding

Algorithm

Step 1 - START
Step 2 - Declare a string namely input_string.
Step 3 - Define the values.
Step 4 - Define a stwtch statement to check the input string and print the respective statements.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Demo {
   public static void main(String[] args) {
      String input_string = "Java";
      System.out.println("The string is defined as: " +input_string);
      System.out.println("Using siwtch cases: ");
      switch (input_string) {
         case "Scala":
            System.out.println("We shall use Scala for our coding");
            break;
         case "Python":
            System.out.println("We shall use Python for our coding");
            break;
         case "Java":
            System.out.println("We shall use Java for our coding");
            break;
         default:
            System.out.println("The string is undefined");
      }
   }
}

Output

The string is defined as: Java
Using siwtch cases:
We shall use Java for our coding

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class Demo {
   static void switch_case(String input_string){
      System.out.println("Using siwtch cases: ");
      switch (input_string) {
         case "Scala":
            System.out.println("We shall use Scala for our coding");
            break;
         case "Python":
            System.out.println("We shall use Python for our coding");
            break;
         case "Java":
            System.out.println("We shall use Java for our coding");
            break;
         default:
            System.out.println("The string is undefined");
      }
   }
   public static void main(String[] args) {
      String input_string = "Java";
      System.out.println("The string is defined as: " +input_string);
      switch_case(input_string);
   }
}

Output

The string is defined as: Java
Using siwtch cases:
We shall use Java for our coding

Updated on: 30-Mar-2022

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements