Learn How To Switch In Java
In this tutorial, you will learn to use the switch Command to control the flow of your program. In Java, the if..else..if ladder executes code from many blocks.
The switch Command can replace long ladders that make the code legible.
The syntax of the switch Command is as follows:
switch (variable / expression) { case value1: // statements break; case value2: // statements break; .. ..… .. ..… default: // statements }
The switch Command evaluates the expression (mostly variable) and compares it with each label’s values (can be an expression).
The switch Command executes all commands of the matching label.
Suppose the variable/expression is equal to value2. In this case, all commands related to this adaptive case are executed.
Note: Use the phrase break to terminate the execution of the switch statement. Break statements are important because if not used, all commands after the matching tag will be executed in sequence until the end of the switch statement.
Flowchart Command switch
It should also be noted that the switch Command in Java only works with the following:
- Initial data types: byte, short, char, and int
- Types (enum (enum Java
- String class
- Character, Byte, Shor,t and Integer classes.
Example 1: Switch Command in Java
- class Day {
- public static void main (String [] args) {
- int week = 4;
- String day;
- switch (week) {
- case 1:
- day = “Sunday”;
- break;
- case 2:
- day = “Monday”;
- break;
- case 3:
- day = “Tuesday”;
- break;
- case 4:
- day = “Wednesday”;
- break;
- case 5:
- day = “Thursday”;
- break;
- case 6:
- day = “Friday”;
- break;
- case 7:
- day = “Saturday”;
- break;
- default:
- day = “Invalid day”;
- break;
- }
- System.out.println (day);
- }
- }
Output
Wednesday
Example 2: Switch Command in Java
The following program receives three inputs from the user: an operator and two numbers. It then performs calculations based on the numbers and operators entered. The result is then displayed.
We used the scanner object to get input from the user.
- import java.util.Scanner;
- class Calculator {
- public static void main (String [] args) {
- char operator;
- Double number1, number2, result;
- Scanner scanner = new Scanner (System.in);
- System.out.print (“Enter operator (either +, -, * or /):”);
- operator = scanner.next (). charAt (0);
- System.out.print (“Enter number1 and number2 respectively:”);
- number1 = scanner.nextDouble ();
- number2 = scanner.nextDouble ();
- switch (operator) {
- case ‘+’:
- result = number1 + number2;
- System.out.print (number1 + “+” + number2 + ”=” + result);
- break;
- case ‘-‘:
- result = number1 – number2;
- System.out.print (number1 + “-” + number2 + ”=” + result);
- break;
- case ‘*’:
- result = number1 * number2;
- System.out.print (number1 + “*” + number2 + ”=” + result);
- break;
- case ‘/’:
- result = number1 / number2;
- System.out.print (number1 + “/” + number2 + ”=” + result);
- break;
- default:
- System.out.println (“Invalid operator!”);
- break;
- }
- }
- }
Output
Enter operator (either +, -, * or /): *
Enter number1 and number2 respectively: 1.4
-5.3
1.4 * -5.3 = -7.419999999999999
Language Introduction History
This mechanism was introduced in Java 12 (JEP 325) as a preview feature. Subsequently, a second preview was presented in Java 13 (JEP 354), and the final functionality was introduced in Java 14 (JEP 361) without any changes. Switch Expressions are part of Project Amber, which also anticipates introducing other practical changes to Java.
Interestingly, in Java 12, the keyword break
was used to return a value:
String season = "Winter"; String translation = switch (season) { case "Spring": break "wiosna"; case "Summer": break "lato"; case "Autumn": break "jesień"; case "Winter": break "zima"; default: break "nieznany"; };
The exact keyword had always been used to exit a case
block. To differentiate between these two uses, starting from Java 13, the keyword yield
must be used when returning a value.
Further Development of the Switch
It can be said that Switch Expression is the first step in the evolution of the switch
Statement. The next stage involves work on Pattern Matching for the final version, which is not expected before JDK 20.
Before Switch Expression was introduced
Before the introduction of this mechanism, we had to handle such scenarios in the following way:
Java
String season = "Winter";
switch (season) {
case "Spring":
System.out.println("Mamy aktualnie wiosnę");
break;
case "Summer":
System.out.println("Mamy aktualnie lato");
break;
case "Autumn":
System.out.println("Mamy aktualnie jesień");
break;
case "Winter":
System.out.println("Mamy aktualnie zimę");
break;
default:
System.out.println("Nie znam takiej pory roku");
}
Most often, however, methods were created to return a result by placing a return
statement within each case
.
Java
static String getTranslation(String season) {
switch (season) {
case "Spring":
return "wiosna";
case "Summer":
return "lato";
case "Autumn":
return "jesień";
case "Winter":
return "zima";
default:
return "nieznany";
}
}
Ultimately, the call would be a single line:
Java
String translation = getTranslation("Winter");