blog posts

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 switchSwitch In Java

 

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

  1. class Day {
  2. public static void main (String [] args) {
  3. int week = 4;
  4. String day;
  5. switch (week) {
  6. case 1:
  7. day = “Sunday”;
  8. break;
  9. case 2:
  10. day = “Monday”;
  11. break;
  12. case 3:
  13. day = “Tuesday”;
  14. break;
  15. case 4:
  16. day = “Wednesday”;
  17. break;
  18. case 5:
  19. day = “Thursday”;
  20. break;
  21. case 6:
  22. day = “Friday”;
  23. break;
  24. case 7:
  25. day = “Saturday”;
  26. break;
  27. default:
  28. day = “Invalid day”;
  29. break;
  30. }
  31. System.out.println (day);
  32. }
  33. }

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.

  1. import java.util.Scanner;
  2. class Calculator {
  3. public static void main (String [] args) {
  4. char operator;
  5. Double number1, number2, result;
  6. Scanner scanner = new Scanner (System.in);
  7. System.out.print (“Enter operator (either +, -, * or /):”);
  8. operator = scanner.next (). charAt (0);
  9. System.out.print (“Enter number1 and number2 respectively:”);
  10. number1 = scanner.nextDouble ();
  11. number2 = scanner.nextDouble ();
  12. switch (operator) {
  13. case ‘+’:
  14. result = number1 + number2;
  15. System.out.print (number1 + “+” + number2 + ”=” + result);
  16. break;
  17. case ‘-‘:
  18. result = number1 – number2;
  19. System.out.print (number1 + “-” + number2 + ”=” + result);
  20. break;
  21. case ‘*’:
  22. result = number1 * number2;
  23. System.out.print (number1 + “*” + number2 + ”=” + result);
  24. break;
  25. case ‘/’:
  26. result = number1 / number2;
  27. System.out.print (number1 + “/” + number2 + ”=” + result);
  28. break;
  29. default:
  30. System.out.println (“Invalid operator!”);
  31. break;
  32. }
  33. }
  34. }

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 SwitchSwitch In Java

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