switch statement in java

Let’s learn switch statement in java.

switch statement in java

Java switch statement tests one variable for equality aganist many code blocks depending on the value of variable.

Variable used in switch statement should be enums, strings, convertable integers (char, byte, short) and integers.

switch statement in java
Flow diagram of switch case

We can have any number of case statements within switch. Value for case must be same data type as variable in switch.

The value of case should be a literal or constant. If the variable being switched is equal to case then statements corresponding to that case will execute until break statement.

switch terminates when it is reached break statement. Then the control shifts to next switch statement.

It’s not mandatory to add break statement in every case. If there’s no break statement then flow of control will continue to next subsequent case until break statement.

It is a good programming practice to have a default case in switch statement which should appear at the end.

default case can be used to perform a task when none of the cases is true.

Valid: switch(5 + 6 + 56) switch(5 * 6 + 7 % 8)
Invalid: switch(pq + rs) switch(p + q + r)

Let’s see syntax of switch statement and switch case in java example programs.

Syntax

switch(expression)
{
   case 1 value :
   // code goes here
   break;

   case 2 value :
   // code goes here
   break;

   case 3 value :
   // code goes here
   break;
   .
   .
   .
   .
   
   default: // optional
   // default code goes here
}


switch case in java example programs

public class SwitchStatementExample
{
   public static void main(String[] args)
   {
      char grade = 'A';
      switch(grade) {
          case 'A' :
              System.out.println("Distinction.");
              break;
          case 'B' :
          case 'C' :
              System.out.println("First class.");
              break;
          case 'D' :
              System.out.println("You have passed.");
          case 'F' :
              System.out.println("Fail. Try again.");
              break;
          default :
              System.out.println("Invalid grade");
      }
      System.out.println("Grade is: " + grade);
   }
}


Output:

Distinction.
Grade is: A


switch enum

Switch statement can be used with java switch enum.

Enum types are special data type that enables variable to be a set of predefined constants.

Let’s see program on switch case enum.

enum Fruit
{
   apple, mango, jackfruit, orange, grapes
}
public class SwitchEnumDemo
{
   public static void main(String[] args)
   {
      Fruit f;
      f = Fruit.mango;
      switch (f) {
          case apple:
              System.out.println("You have selected apple.");
              break;
          case mango:
              System.out.println("You have selected mango.");
              break;
          case jackfruit:
              System.out.println("You have selected jackfruit.");
              break;
          case orange:
              System.out.println("You have selected orange.");
              break;
          case grapes:
              System.out.println("You have selected grapes.");
              break;
          default:
              System.out.println("Invalid selection!");
              break;
      }
   }
}


Output:

You have selected mango.


java switch statement string

Since JDK 7 string literal was used in switch case.

String in switch statement is an expensive operation when we compare with primitive data types.

Here string should not be null in switch statement expression to prevent NullPointerException.

Here comparison is case sensitive. Because expression in switch statement compares String object with each label using String.equals() method.

String in switch case is better than if-else statement. Now let’s learn an example on java switch statement string.

public class SwitchStringJava 
{
   public static void main(String[] args) 
   {
      String str = "twelve"; 
      switch(str) 
      { 
         case "ten": 
             System.out.println("ten"); 
             break;
         case "eleven": 
             System.out.println("eleven"); 
             break;
         case "twelve": 
             System.out.println("twelve"); 
             break; 
         default: 
             System.out.println("doesn't match"); 
      }
   }
}


Output:

twelve


grade program using switch statement

Now let’s see grade program using switch statement in java. Here we have to compute marks based on given grades.

So if grade is A then marks will be greater than or equal to 80, if grade is B then marks will be greater than or equal to 60 and less than 80.

If grade is C then marks will be greater than or equal to 40 and less than 60. Lastly if grade is F then marks will be less than or equal to 40.

Print invalid grade if any other grade is typed by user. Here’s the grade program using switch statement.

import java.util.Scanner;
public class GradeSwitch 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter grade from A, B, C or F: ");
      String strInput = sc.next();
      char grade = strInput.charAt(0);
      switch (grade) 
      {
         case 'A':
             System.out.println("Grade A - distinction");
             break;
         case 'B':
             System.out.println("Grade B - first class");
             break;
         case 'C':
             System.out.println("Grade C - second class");
             break;     
         case 'F':
             System.out.println("Grade F - fail");
             break;
         default:
             System.out.println("invalid grade");
             break;
      }
      sc.close();
   }
}


Output:

Please enter grade from A, B, C or F): A
Grade A – distinction

Please enter grade from A, B, C or F): E
invalid grade


java switch multiple case

In the rearest case we need to perform multiple case in switch statement. To do that use java switch multiple case.

Let’s see an example on java switch multiple case for better understanding.

public class SwitchMultipleCase
{
   public static void main(String[] args)
   {
      System.out.println(multipleCase("one"));
      System.out.println(multipleCase("two"));
   }
   static String multipleCase(final String number)
   {
      String str = null;
      switch(number)
      {
         case("one"):
         case("three"):
         case("five"):
             str = "odd numbers";
         break;

         case("two"):
         case("four"):
         case("six"):
             str = "even numbers";
         break;
         default:
             str = "please enter valid input";
      }
      return str;
   }
}


Output:

odd numbers
even numbers


java switch case multiple values

Let’s learn to check multiple values in single switch statement. Here’s an example on java switch case multiple values.

public class SwitchCaseMultipleValues
{
   public static void main(String[] args)
   {
      int number = 1;
      switch(number)
      {
         case 1: case 2:
             System.out.println("number 1");
             System.out.println("number 2");
             break;
         case 3:
             System.out.println("number 3");
             break;
         default:
             System.out.println("number is not 1, 2 or 3");
      }
   }
}


Output:

number 1
number 2

This is all about switch statement in java. Switch case program in java questions.

Hope this post would be helpful for java interview for freshers.