Slide 1
Slide 2
Slide 3

Switch statement in java programming (V37)

No Comments

Switch Statement

A switch statement is used to test a list of values known as cases. Each value inside the case list is checked, and when a match is found, the corresponding block of code is executed. If no matching case is found, the default block can optionally be executed.

A switch statement can be used when multiple if-else statements are required. It can contain multiple code blocks with case values and will execute only one code block based on the matching case value.

Syntax:

Rules for Using switch Statement

  • The variable used in a switch statement can be an integer or any data type that can be converted to an integer (such as byte, short, char), strings, or enums.

  • You can have multiple case statements inside a switch. Each case is followed by a value that will be compared with the variable.

  • The value for a case must be of the same data type as the variable in the switch, and it must be a constant or literal.

  • When the variable being switched matches a case, the statements after that case will execute until a break statement is encountered.

  • When a break statement is reached, the switch will terminate, and the program continues to the next line after the switch statement.

  • Not all cases require a break statement. If no break appears, the control flow will continue to the next case (this is called fall-through) until a break is found.

  • A switch statement may optionally have a default case, which must appear at the end of the switch. The default case is used to execute code when none of the cases match. A break is not required in the default case.

Flow Diagram


Source Code:

Copied!
import java.util.Scanner;
public class Grade {

   public static void main(String args[]) {
   	Scanner scanner = new Scanner(System.in);
   	
	  System.out.print("Enter Grade : ");
	  char grade = scanner.next().charAt(0);
      switch(grade) {
         case 'A' :
            System.out.println("Excellent!"); 
            break;
         case 'B' :
         case 'C' :
            System.out.println("Well done");
            break;
         case 'D' :
            System.out.println("You passed");
         case 'F' :
            System.out.println("Better try again");
            break;
         default :
            System.out.println("Invalid grade");
      }
      System.out.println("Your grade is " + grade);
   }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top