Java Switch Statement Explained [Easy Examples]

 

Introduction to Java switch statement

A switch statement is a multiple-branch statement in Java. The java switch statement successively checks the value of an expression with a list of integer or character constants. The data type of expression in a switch can be byte, char, short, or int. When a match is found, the statements associated with that constant are executed.

In this tutorial, we will see how we can apply the java switch statement to different data types. Moreover, we will also discuss java switch yield Instruction and Java switch Expression Use Cases.

Advertisement

In a nutshell, this is going to be one of the informative tutorials about java switch statement.

 

Getting started with Java switch statement

A Java switch statement enables us to select a set of statements to execute based on the value of some variable. This is in effect somewhat similar to the java if statement, although the Java switch statement offers more compressed syntax, and a slightly different behavior than the other java conditional statements. We can apply the java switch statements on various different kinds of data types which we will discuss in a later section.

 

The general syntax of the java switch statement (without break)

The switch statement evaluates the expression and matches the values against the constant values which are specified in the case statements. When a match is found, the statement associated with that case is executed until it encounters a break statement, or else the switch statement ends. When no match is found, the default statement gets executed. In the absence of a break, the control flow moves to the next case below the matching case and this is called fall through.

 

The simple syntax of java switch statement without break statement looks like this:

switch (expr)
{
    case value1:
    statement1;
    case value2:
    statement2;
    .
    .
    .
    case valueN:
    statementN;
    default:
    statementDefault;
}

Notice that there is no any break statement so even if we found the best match, the next cases will also be checked. To void this checking after finding the best case, we use break statements.

 

The general syntax of the java switch statement (with break)

The syntax of java switch with break statements looks like this;

Advertisement
switch (expr)
{
    case value1:
    statement1;
    break;
    case value2:
    statement2;
    break;
    .
    .
    .
    case valueN:
    statementN;
    break;
    default:
    statementDefault;
}

Notice that there is no break statement inside the default block because we don't actually need a break statement inside it. If you want to put, you can, it will not return any error. It will just take an extra line because anyways the code is going to break/finished after the default case as there are no further cases.

 

If else vs java switch statements

Java switch works in a similar way to java if-else statements but sometimes using switch statements is much easier and faster than if-else statements. In this section, we will first take an example of an if-else statement and then we will solve the same example using java switch statements as well you can easily see how they are similar to each other.

See the example of an if-else statement below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {
        int num = 19;
    // java if else statements
    if (num==0){
        System.out.println("The number is zero");
    } else if (num==5){
        System.out.println("The number is 5");
    } else if (num==15){
        System.out.println("The number is 15");
    } else{
        System.out.println("we couldn't find the number");
    }

  }  
} 

Output:

we couldn't find the number

Now let us perform the same action using the java switch statement as well. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {
        int num = 19;
    // java switch statement
    switch(num){
        case 0:
            System.out.println("The number is zero");
            break;
        case 5:
            System.out.println("The number is five");
            break;
        case 15:
            System.out.println("The number is 15");
            break;
        default:
            System.out.println("we couldn't find the number");
    }
  }  
} 

Output:

we couldn't find the number

Notice that we perform the same operation using the switch statement as we did by using if-else statements.

 

Java switch on different data types

We already had used an example of a java switch statement in the above example which uses a variable.  The new version of Java supports this variable to be a byte, short, char, int, and string. You can read more about java bytes from java operator article. In the following sections, take examples of each of these data types with Java switch statements.

Advertisement

 

Example-1: Java switch on byte

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays where the memory savings actually matters.

Let us take an example and see if java supports bytes in switch statements. See the example below.

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {
        // byte data type
        byte num = 19;
    // java switch statement
    switch(num){
        case 0:
            System.out.println("The number is zero");
            break;
        case 5:
            System.out.println("The number is five");
            break;
        case 15:
            System.out.println("The number is 15");
            break;
        default:
            System.out.println("we couldn't find the number");
    }
  }  
}  

Output:

we couldn't find the number

Notice that the type was byte.

 

Example-2: Java switch and short data type

The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). In this section, we will take short data typed variables and use them in switch statements. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {
        // short data type
        short num = 15;
    // java switch statement
    switch(num){
        case 0:
            System.out.println("The number is zero");
            break;
        case 5:
            System.out.println("The number is five");
            break;
        case 15:
            System.out.println("The number is 15");
            break;
        default:
            System.out.println("we couldn't find the number");
    }
  }  
} 

Output:

The number is 15

Notice that the input variable was a short data type.

 

Example-3: Java switch and char data type

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). In this section, we will take an example of char data typed variable used in a switch statement. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {
        // char data type
        char size = 'L';
    // java switch statement
    switch(size){
        case 'S':
            System.out.println("Your T-shirt size is Small");
            break;
        case 'M':
            System.out.println("Your T-shirt size is Medium");
            break;
        case 'L':
            System.out.println("Your T-shirt size is Large");
            break;
        default:
            System.out.println("No size available");
    }
  }  
} 

Output:

Your T-shirt size is Large

Notice that the data type was a char data typed.

 

Example-4: Java switch and string data type

A Java String is a sequence of characters that exist as an object of the class java. Java strings are created and manipulated through the string class. Once created, a string is immutable which means its value cannot be changed. In this section, we will take strings with switch statements. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {
        // char data type
        String size = "medium";
    // java switch statement
    switch(size){
        case "small":
            System.out.println("Your T-shirt size if Small");
            break;
        case "medium":
            System.out.println("Your T-shirt size if Medium");
            break;
        case "large":
            System.out.println("Your T-shirt size if Large");
            break;
        default:
            System.out.println("No size available");
    }
  }  
} 

Output:

Your T-shirt size if Medium

If we take any other data type that is not supported by the java switch, we will get an error. See the example below which uses float data type in the switch, so we get the following error.

java switch statement

 

Example-5: Java switch on Java enum

A Java Enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods, etc. In this section, we will take java enum with switch statements. See the example below which first stores all constants and then used those to print the names of days:

// class
public class Main  { 
    // java anum
    public enum Days {  Sun, Mon, Tue, Wed, Thu, Fri, Sat  }    
    public static void main(String args[])    
    {    
      // creating arrays for days
      Days[] Today = Days.values();  
        // for loop  
        for (Days Now : Today)    
        {    
            // switch statement 
             switch (Now)    
             {    
                 case Sun:    
                     System.out.println("Sunday");    
                     break;    
                 case Mon:    
                     System.out.println("Monday");    
                     break;    
                 case Tue:    
                     System.out.println("Tuesday");    
                     break;         
                 case Wed:    
                     System.out.println("Wednesday");    
                     break;    
                 case Thu:    
                     System.out.println("Thursday");    
                     break;    
                 case Fri:    
                     System.out.println("Friday");    
                     break;    
                 case Sat:    
                     System.out.println("Saturday");      
             }    
         }    
     }   
} 

Output:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

 

Summary

The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. In this tutorial, we learned about java switch statements.

We learned the basic syntax of the java switch statement with and without a break statement and we discussed why we used the break statements in the java switch statment. Moreover, we covered all the data types that are supported by java switch statements. We take various examples of the supported data types with switch statements. All in all, this tutorial covers each and every concept that you need to know in order to get started with a switch statement.

 

Further Reading

java switch 
More about java switch statements
if-else in java

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment