Sunday, December 4, 2022
HomeJavaThings you don't know about the Java Switch statement

Things you don’t know about the Java Switch statement

Using various circumstances, the Java switch statement executes a single expression. It is similar to an if-else-if expression. The byte, short, int, long, enum types, string, and wrapper types like Byte, Short, Int, and Long are all compatible with the switch statement. Since Java 7, the switch statement supports Strings. 

What is a Java Switch statement?

The switch statement is a single expression that executes a large number of conditional operations, which is also similar to the if-else-if statement but this is written in simpler form equality of variable in front of multiple values. With the help of multiple conditions, one of the statements is executed.

A switch block is the main portion of a switch statement. A switch block statement may have one or more case or default labels attached to it. All statements that follow the appropriate case label are then carried out by the switch statement after its expression has been evaluated. 

The break statement is another interesting point. The switch statement that is enclosed in each break statement is terminated. The first sentence after the switch block continues the control flow. Statements in switch blocks fail if there are no break statements, hence they are required: Until a break statement is met, all statements after the matching case label are carried out in order, regardless of the expression of succeeding case labels.

The switch block statements that fail to execute are displayed by the application SwitchDemoFallThrough. The program shows the month that corresponds to the integer month as well as the succeeding months in the year. 

Also read, Understanding Java Math Class And its different methods

Important rules to write Switch case

No Variables

A literal or constant must be used as the case value in switch statements. Additionally, it needs to be of the same type as a switch expression.

No Duplicates

In a switch statement, no two cases should have the same value. If repeated it will be showing an error or you might be having problems.

Allowed Types

The int, long, byte, short, enums, and String types must all be present in the Java switch expression. The types of their wrappers are acceptable for primitives.

Optional Break Statement

The switch statement in Java has an optional break clause. The next case is run until a break statement or the end of the switch statement is encountered if a case is matched and no break statement is given. 

Optional Default Statement

When there is no match between the variable’s values and the cases, the default statement is supposed to be used. Depending on the desired outcome, it can be positioned wherever you choose in the switch block. 

Syntax

 switch(expression) { 
  case x: 
    // code block 
    break; 
  case y: 
    // code block 
    break; 
  default: 
    // code block 
}

Flowchart

Java switch statement

Also read, Understanding Java String methods with examples

Different cases for switch with examples

Passing String

The comparison of String objects in switch statements is case sensitive because the switch statement compares the String object in its expression with the expressions linked to each case label as if it were using the String.equals function. Switch statements that use String objects are often more efficient bytecode generators for Java than chained if-then-else expressions. 

Also known as a case-sensitive comparison the equals() function of the String class is used by the switch statement to compare the String object in its expression with the expressions associated with each case label; as a result, the comparison of String objects in switch statements is case sensitive. 

Example

public class Main
{
    public static void main(String[] args) {
        String game = "Cricket";   
        switch(game){   
            case "Hockey":   
                System.out.println("We will be playing Hockey");   
                break;   
            case "Cricket":   
                System.out.println("We will be playing Cricket");   
                break;   
            case "Football":   
                System.out.println("We will be playing Football"); 
        }
    }
}


// Output : We will be playing Cricket

Also read, How to Contribute to Open Source – a Guide for Technical Writers

Passing Number

The switch case statement is most used for passing numbers which makes it easy for the programmer to code in a simple short way and it accepts ‘n’ numbers of cases, so it doesn’t have a limit. Passing numbers is very easy as you only need integers to run your code.

Example

public class Main
{
  public static void main (String[]args)
  {
    int day = 4;
    switch (day)
      {
      case 1:
        System.out.println ("Day 1: Monday");
        break;
    case 2:
        System.out.println ("Day 2: Tuesday");
        break;
    case 3:
        System.out.println ("Day 3: Wednesday");
        break;
    case 4:
        System.out.println ("Day 4: Thursday");
        break;
    case 5:
        System.out.println ("Day 5: Friday");
        break;
    case 6:
        System.out.println ("Day 6: Saturday");
        break;
    case 7:
        System.out.println ("Day 7: Sunday");
    }

  }
}

If no numbers matched

If none of your numbers matches with the cases, there is a default statement that we implement for such cases; so if none of your cases match then it will print the default statement.

The default statement is used for such scenarios. The default statement will be executed at the end of the day if the variable in this scenario is given the value 9, after which all cases will be checked to see whether the equality criteria can be met with this value.

Example

public class Main
{
  public static void main (String[]args)
  {
    int day = 12;
    switch (day)
      {
      case 1:
        System.out.println ("Day 1: Monday");
        break;
    case 2:
        System.out.println ("Day 2: Tuesday");
        break;
    case 3:
        System.out.println ("Day 3: Wednesday");
        break;
    case 4:
        System.out.println ("Day 4: Thursday");
        break;
    case 5:
        System.out.println ("Day 5: Friday");
        break;
    case 6:
        System.out.println ("Day 6: Saturday");
        break;
    case 7:
        System.out.println ("Day 7: Sunday");
        break;
    default:
        System.out.println("Invalid number");
    }
  }
}


// Output : Invalid number

If we don’t use the ‘break’ statement

When we forget to include break statements in switch situations, the statement is referred to as a fall-through statement. When a case in such a situation succeeds, all the following cases also run until a break statement or the end of the switch block is reached.

In the below example after entering 9, the statements from 9 to 12 and the result for the default statement will be printed.

Example

public class Main
{
  public static void main (String[]args)
  {
    int num = 9;
    switch (num)
      {
      case 1:
        System.out.println ("January");
        break;
    case 2:
        System.out.println ("February");
        break;
    case 3:
        System.out.println ("March");
        break;
    case 4:
        System.out.println ("April");
        break;
    case 5:
        System.out.println ("May");
        break;
    case 6:
        System.out.println ("June");
        break;
    case 7:
        System.out.println ("July");
        break;
    case 8:
        System.out.println ("August");
        break;
    case 9:
        System.out.println ("September");
    case 10:
        System.out.println ("October");
    case 11:
        System.out.println ("November");
    default:
        System.out.println ("Invalid number");
      }
  }
}


// Output : 
// September
// October
// November
// Invalid number

Also read, Understanding Java Conditional Statement with Flowcharts

Final Words

As we have read from the above we can clearly see that we use switch statements just like any other buttons at your home for an electric connection, if we press the button for the fan; the fan will turn on similar to that the switch statement works. If you go by the rules mentioned above, you will get an idea of the switch statement.

The comparison between a variable and its potential values occurs in the switch case statement. The break statement is used to exit the switch block right away without doing any additional comparisons.

Only when there are no cases with values identical to the variable value will the default statement be carried out. When we forget to include break statements in switch situations, the statement is referred to as a fall-through statement. With independent variable values, we can nest one switch statement inside another switch expression. In Java switch statements, enum and wrapper classes can be used.

Ali Hashir
Hi, I am a High School student, who is highly interested in tech, gadgets, and Gaming. With my knowledge and experience, I want to share my thoughts so that you can decide what better for you.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments