JAVA LESSON 10 – THE SWITCH STATEMENT

 


INTRODUCTION

In the previous free Java lesson, we saw how we can add to our code the ability to follow a different execution flow depending on the result of a certain condition. Checking the condition was the first step in a series of if-else checks that followed.

In today's free Java lesson, we will see how we can follow a similar logic using the switch statement.

SWITCH SYNTAX AND EXPLANATION

Syntactically, there are quite a few differences between the switch and if-else statements, but both follow a common logic in the way they produce the desired outcome.

If you recall from the previous section, in the if-else statements we performed a series of checks, and the first condition that returned true was the one that determined the execution flow of our code.

Although we will take a detailed look at the structure and syntax of the switch statement, it's worth mentioning that the biggest difference from if-else statements is that we cannot use relational operators (such as =, <=, etc.) in the conditions.

Let’s first take a look at what a Java code snippet that uses the switch statement looks like, and then we’ll explain in detail how it works.

App.java

package com.example;


public class App {


public static void main(String[] args) {

char grade = 'B';

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");

break;

case 'F':

System.out.println("Better try again");

break;

default:

System.out.println("Invalid grade");

break;

}

System.out.println("Your grade is a " + grade);

}

}

Output

Our program begins by assigning a character to a variable named grade. In the very next line of code, we define the start of a switch, and inside the parentheses we pass the variable that the switch will evaluate. Depending on its value, it will execute different code. Starting from Java version 7, the types of values that switch can accept include byte, short, int, char, enumerations, or String. In our example, it is a char.

The value of the variable is compared with each of the cases we have defined. If the case value matches the value of the variable, then the code that follows the colon (:) will be executed. If none of the cases match, then the default case will be triggered. Although the default option is optional, it is considered best practice to use it so that our program always has a block of code to execute, even if none of the cases are matched.

You may have also noticed that in each case, after the code ends, there is a break statement. The use of break stops the execution of the code at that point and prevents it from continuing to the code in the next case. If break is not present, then all the lines of code from the following cases will be executed until a break is found. If there is no break at all, then all the code will be executed, including the default. This happens because the variable is compared to the cases only once. For the first case where the comparison matches, Java executes the code for that case and all the cases that follow until it encounters a break.

We can use this property of break to our advantage. For example, in the case B there is no break. The reason is simple: we want the same code—“Well done”—to be executed whether the variable has the value B or C.

Let's look at another program where we use int values in the switch. Notice that when comparing numbers, we do not use quotes.

App.java

package com.example;


public class App {


public static void main(String[] args) {

int floor = 3;

switch (floor) {

case 1:

System.out.println("Going to the first floor");

break;

case 2:

System.out.println("Going to the second floor");

case 3:

System.out.println("Going to the third floor");

break;

default:

System.out.println("Going Floor Level");

break;

}

System.out.println("You are in floor " + floor);

}

}

Output

The two previous programs follow the classic way of using the switch, which relies on break to execute the code for the selected case and then continue the program execution outside of the switch. Starting from Java 13, the switch can be used as a statement that returns a value to a variable by using the yield keyword.

Let's see how we could rewrite our first program using the innovations provided by the modern versions of Java.

App.java

package com.example;


public class App {


public static void main(String[] args) {

char grade = 'B';

String message = switch (grade) {

case 'A':

yield "Excellent!";

case 'B', 'C':

yield "Well done";

case 'D':

yield "You passed";

case 'F':

yield "Better try again";

default:

yield "Invalid grade";

};

System.out.println("Your grade is a " + grade);

System.out.println(message);

}

}

Output

There is an even more improved way that reduces the code further, and that is by using expressions.

App.java

package com.example;


public class App {


public static void main(String[] args) {

char grade = 'B';

switch (grade) {

case 'A' -> System.out.println("Excellent!");

case 'B', 'C' -> System.out.println("Well done");

case 'D' -> System.out.println("You passed");

case 'F' -> System.out.println("Better try again");

default -> System.out.println("Invalid grade");

}

System.out.println("Your grade is a " + grade);

}

}

Output

Don't forget to make a small donation so that this blog can grow even more and have more capabilities in delivering free online lessons.


full-width

Post a Comment

0 Comments