switch case in java

Java switch Statement with Example | Java Tutorial

The Java switch statement executes a single statement based on a set of conditions. It’s similar to an if-else-if ladder statement. The switch statement supports byte, short, int, long, enum, String, and some wrapper types such as Byte, Short, Int, and Long. Strings can be used in the switch statement since Java 7.

  • When we have a number of options (or choices), we use a switch case statement to perform a different task for each choice.

In Java, the switch statement has the following syntax:

// Switch statement syntax
switch(expression)
{
// case statements
// Values must be of the same expression type.
case value1 :
// …Statements
break; // break is optional
case value2 :
// …Statements
break; // break is optional
// The default statement is shown below, and it is used when none of the cases are true.
// In the default case, no break is required.
default :
// … default Statements
}
  • The expression is evaluated once and compared to the values of each case. If the expression matches value1, the code of case value1 is executed. Similarly, if the expression matches value2, the code for case value2 is executed.
  • If there is no match, the code from the default case is executed.

Some Important Switch Statement Rules:

  • Case values that are duplicated are not permitted.
  • A case value must be a constant or a literal. Variables are not permitted.
  • A case value must be the same data type as the variable in the switch.
  • To end a statement sequence, use the break statement inside the switch.
  • The break statement is not required. If this field is left blank, execution will proceed to the next case.
  • The default statement is optional and can appear at any point within the switch block. If it is not at the end, a break statement must be added after the default statement to prevent the next case statement from being executed.

Switch case Example

// using the switch...case statement

class Main {
  public static void main(String[] args) {

    int value = 35;
    String size;

    // switch statement to check size
    switch (value) {

      case 5:
        size = "Small";
        break;

      case 15:
        size = "Medium";
        break;

      case 25:
        size = "Large";
        break;

      case 35:
        size = "More than Large";
        break;
      
      default:
        size = "Unknown";
        break;

    }
    System.out.println("Size is: " + size);
  }
}

output:

Size is : More than Large

Nested Switch Case statements

A switch statement can be used inside another switch statement. In Java, this is referred to as nested switch-case statements. Any case of an outer switch will include the inner switch statement. Only if the outer switch statement condition is true will the inner switch statement be executed.

// Java program to show nested switch case statement
public class Sample {
	public static void main(String[] args)
	{
		String Branch = "IT";
		int year = 2;

		switch (year) {
		case 1:
			System.out.println("Courses : Compiler design ");
			break;
		case 2:
			switch (Branch) // nested switch
			{
			case "IT":
			case "ECE":
				System.out.println("Courses : Machine Learning");
				break;

			case "CSE":
				System.out.println("Courses : AEM ");
				break;

			default:
				System.out.println("Courses : English");
			}
		}
	}
}

Output:

Courses : Machine Learning

Break statement in Switch Case

To end a statement sequence, use the break statement inside the switch. When a break statement is reached, the switch is terminated, and control is transferred to the line following the switch statement. The break statement is optional. If this field is left blank, execution will proceed to the next case.

public class Sample {

   public static void main(String args[]){
      int n=2;
      switch(n)
      {
	 case 1:
	   System.out.println("Case1 ");
	 case 2:
	   System.out.println("Case2 ");
	 case 3:
	   System.out.println("Case3 ");
	 case 4:
           System.out.println("Case4 ");
	 default:
	   System.out.println("default ");
      }
   }
}

output:

Case2
Case3
Case4
Default

In the preceding program, we passed the integer value 2 to the switch, causing the control to switch to case 2, but there is no break statement after case 2, causing the flow to continue until the end. The break statement is the solution to this problem.

When you want your program flow to exit the switch body, use a break statement. Whenever a break statement is encountered in the switch body, the execution flow will exit the switch, ignoring the remaining cases.

Let’s use the same example as before, but this time with a break statement.

break statement Example

public class Sample {

   public static void main(String args[]){
      int n=2;
      switch(n)
      {
	 case 1:
	   System.out.println("Case1 ");
	   break;
	 case 2:
	   System.out.println("Case2 ");
	   break;
	 case 3:
	   System.out.println("Case3 ");
	   break;
	 case 4:
           System.out.println("Case4 ");
           break;
	 default:
	   System.out.println("default ");
      }
   }
}

Output:

Case2

2: A Java program that demonstrates how to use switch statements with strings.

public class Sample
{
    public static void main(String[] args) {
        String Language="java";
        switch(Language)
        {
            case "Kotlin":
                System.out.println("Kotlin used in Android development");
                break;
            case "java":
                System.out.println("Java used in Mobile App Development, Desktop GUI Applications, Web-based Applications");
                break;
            case "c++":
                System.out.println("C ++ used in web browsers , database");
                break;
            
        }
    }
}

Output:

Java used in Mobile App Development, Desktop GUI Applications, Web-based Applications

3: A Java program that demonstrates the use of a switch case with an enum

public class Sample
{
    
        enum Language
        {
            Kotlin,Java,C++
            
        }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        Language[] CurrentLanguage = Language.values();    
        
       for(Language X:CurrentLanguage)
       {
           switch(X)
           {
               case Kotlin:
                    System.out.println("Kotlin used in Android development");
                    break;
               case Java:
                   System.out.println("Java used in Mobile App Development, Desktop GUI Applications, Web-based Applications");
                   break;
                case C++:
                    System.out.println("C ++ used in web browsers, database");
                    break;
                    
           }
           
       }
    }
}

Few points about the Switch Case

switch case java,switch case java,switch case java,switch case java,switch case java,switch case java,switch case java,switch case java,switch case program in java switch case program in java switch case program

When using switch case statements in Java, there are a few rules that must be followed.

  • In a switch case statement, case values can only be integers, strings, or enums.
  • A switch-case block can contain an unlimited number of cases. You are free to have as many as you want. Each case block is preceded by the case value and a colon( : ). The code that will be executed when the case is true follows.
  • Keep in mind that the value and data type must be the same as the variable in the switch block.
  • Cases do not allow for expressions. The value can only be literal or constant.
  • When a case evaluates to true, the compiler will execute each statement line by line until it encounters a break statement.
  • The control shifts to the lines following the switch block as soon as the compiler passes through a break statement.
  • The switch case in Java is a fall-through case. This means that if no break statement is present in a case block, the program’s control will continue to loop through all of the cases.
  • If no case evaluates to true, the default case (if it exists) is executed.
  • Each case value must be unique.

You May like:

Java Input and Output | Java Tutorial

Operators in Java | Java Tutorial

Java Data Types | Primitive and Non-Primitive Data Types

We hope that this article will assist you in understanding all about switch case in Java. We have concentrated on making a basic, meaningful, and easy-to-learn guide to the concepts. Still, if you have any problems regarding this, please post them in the comment section, and we will be glad to assist you.

switch case example, switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example , switch case example

This Post Has 5 Comments

Leave a Reply