CodeGym /Courses /Java Syntax Zero /Java's multiple-choice operator: switch

Java's multiple-choice operator: switch

Java Syntax Zero
Level 14 , Lesson 7
Available

1. The multiple-choice operator: switch

Java has another interesting operator that it inherited from its grandpappy (C++). We're talking about the switch statement. We could also call it a multiple-choice operator. It looks a little cumbersome:

switch(expression)
{
   case value1: code1;
   case value2: code2;
   case value3: code3;
}

An expression or variable is indicated within the parentheses. If the value of the expression is value1, the Java machine starts executing code1. If the expression is equal to value2, execution jumps to code2. If the expression is equal to value3, then code3 is executed.

Example:

Code Console output
int temperature = 38;

switch(temperature)
{
   case 36: System.out.println("Low");
   case 37: System.out.println("Normal");
   case 38: System.out.println("High");
} 
High

2. break statement in switch

An important feature of a switch statement is that the program simply jumps to the required line (to the required code block) and then executes all the blocks of code until the end of the switch. Not only the block of code corresponding to the value in the switch, but all the blocks of code until the end of the switch.

Example:

Code Console output
int temperature = 36;

switch(temperature)
{
   case 36: System.out.println("Low");
   case 37: System.out.println("Normal");
   case 38: System.out.println("High");
} 
Low
Normal
High

Given a temperature of 36, the program will enter the switch statement, jump to and execute the first block of code (the first case), and then cheerfully execute the rest of the blocks of code.

If you want to execute only one block of code — the block of code associated with the matched case — then you need to end the block with a break statement;

Example:

Code Console output
int temperature = 36;

switch(temperature)
{
   case 36:
      System.out.println("Low");
      break;
   case 37:
      System.out.println("Normal");
      break;
   case 38:
      System.out.println("High");
}
Low

You can omit the break in the last case of the switch statement, since that block is the last with or without a break statement.


3. Default action: default

Another important point. What happens if none of the cases listed in the switch match the expression in the parentheses?

If a matching case is not found, then the rest of the switch statement is skipped, and the program will continue execution after the curly brace ending the switch statement.

That said, you can also make a switch statement behave like the else branch in an if-else statement. To do this, use the default keyword.

If none of the cases in the switch block match the value of the expression and the switch has a default block, the default block will be executed. Example:

Code Console output
int temperature = 40;
switch(temperature)
{
   case 36:
      System.out.println("Low");
      break;
   case 37:
      System.out.println("Normal");
      break;
   case 38:
      System.out.println("High");
      break;
   default:
      System.out.println("Call an ambulance");
}
Call an ambulance

4. Comparing switch and if-else

The switch statement is somewhat similar to an if-else statement, only more complicated.

You can always rewrite the code of a switch statement as multiple if statements. Example:

Code with switch Code with if-else
int temperature = 40;
switch(temperature)
{
   case 36:
      System.out.println("Low");
      break;
   case 37:
      System.out.println("Normal");
      break;
   case 38:
      System.out.println("High");
      break;
   default:
      System.out.println("Call an ambulance");
} 
int temperature = 40;

if (temperature == 36)
{
   System.out.println("Low");
}
else if (temperature == 37)
{
   System.out.println("Normal");
}
else if (temperature == 38)
{
   System.out.println("High");
}
else
{
   System.out.println("Call an ambulance");
}

The code on the left will work exactly the same as the code on the right.

A chain of multiple if-else statements is preferable when an if statement contains various complex expressions in each separate case.


14
Task
New Java Syntax, level 14, lesson 7
Locked
20 words that start with the letter "L"
You need to create a set of strings (using HashSet) and add 20 words that start with the letter "L".
14
Task
New Java Syntax, level 14, lesson 7
Locked
Greater than 10? You're not a good fit for us
Create a set of numbers (Set) and add 20 different numbers to it. Remove from the set all numbers greater than 10.

5. What expressions can be used in a switch statement?

Not all types can be used as case labels in a switch statement. You can use literals of the following types:

  • integer types: byte, short, int, long
  • char
  • String
  • any enum type

You cannot use any other types as case labels.

Example of using an enum inside a switch statement:

Day day = Day.MONDAY;
switch (day)
{
   case MONDAY:
      System.out.println("Monday");
      break;
   case TUESDAY:
      System.out.println("Tuesday");
      break;
   case WEDNESDAY:
      System.out.println("Wednesday");
      break;
   case THURSDAY:
      System.out.println("Thursday");
      break;
   case FRIDAY:
      System.out.println("Friday");
      break;
   case SATURDAY:
      System.out.println("Saturday");
      break;
   case SUNDAY:
      System.out.println("Sunday");
      break;
}

Note: If you use an enum inside a switch statement, you don't need to write the class name in front of each value in the case labels. It is enough to just write the value.


14
Task
New Java Syntax, level 14, lesson 7
Locked
Census
Create a Map and add ten entries that represent (last name, first name) pairs. Check how many people have the same first name or last name.
14
Task
New Java Syntax, level 14, lesson 7
Locked
We don't need repeats
Create a Map and add ten entries that represent (last name, first name) pairs. Remove people with the same first name.
14
Task
New Java Syntax, level 14, lesson 7
Locked
Remove all people born in the summer
In the Map, add ten entries that represent (last name, birth date) pairs. Remove from the map all people born in the summer.
14
Task
New Java Syntax, level 14, lesson 7
Locked
Only for the rich
Create a Map and add ten entries that represent (last name, salary) pairs. Remove from the map all people whose salary is below 500.
Comments (5)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Marcel Level 23, Stuttgart, Deutschland Expert
15 May 2024
The variable names in the "correct solution" for the "from switch to if" task are somewhat misleading. Don't let that confuse you.
Pekotski Level 16, Zurich, Switzerland
6 March 2024
Another winner in crappy lessons.
Kyle Akuya (Wicked98) Level 18, United States of America, United States
5 December 2023
yes, last lesson task , needs the method name changed , I was unsure what errors were happening until I looked at the directions more closely
Xm Level 24, Israel
18 November 2023
LAST QUEST IS DEFECT, REQUIRES ANOTHER METHOD NAME INSTEAD OF IRIGIN
Anonymous #11008702 Level 27, Lewisburg, United States
29 June 2022
14.7.5 the solution is incorrect, this is broken, this is a DEFECT The result of the getShapeNameByCornerCount(int) method should not change. It would not accept a correct solution. Instead, it requires you to change the method to getShapeNameByCountOfCorners (WTF!!!) How are we supposed to know that, when the instructions specifically state the method name is getShapeNameByCornerCount in 3 places. Please fix this obvious defect. Here is my syntactically correct, but rejected submission: Compare my submission with the "correct" solution here > https://www.diffchecker.com/diff package en.codegym.task.pro.task13.task1322; public class Solution { public static void main(String[] args) { System.out.println(getShapeNameByCornerCount(3)); System.out.println(getShapeNameByCornerCount(5)); System.out.println(getShapeNameByCornerCount(1)); } public static String getShapeNameByCornerCount(int cornerCount) { switch (cornerCount) { case 3: return "Triangle"; case 4: return "Quadrangle"; case 5: return "Pentagon"; case 6: return "Hexagon"; case 7: return "Heptagon"; case 8: return "Octagon"; default: return "Other shape"; } } }