Switch Statement with Example in Java

In this class, We discuss Switch Statement with Example in Java.

The reader should have prior knowledge of if elseif else statements. Click Here.

First, we take an example and understand the execution of the switch statement.

Once we understand the execution sequence, we discuss the situation where we use a switch statement.

Example:

The below diagram shows an example.

num = 2

switch(num)

the statement switch takes a variable.

The body of the switch contains case 1, case 2, etc.

The num value is 2.

the switch statement will execute case 2.

The num value matches case 2:

The block of code belonging to case 2 will execute.

After writing the code block at the end, we write a break statement.

The switch statement executes from case 2 until it finds the break statement.

So at the end of each case break statement should be written.

The default will execute if the num does not match any of the cases.

Output: Executing Two player

In which situation switch statement is used?

Suppose we opened a video game.

The game shows a message that selects any of the players.

If the user selects 1, it is a single player.

If the user selects 2, it is a double player so on.

The code belongs to a single player, and the two-player is different.

So the block of code that should be executed for a single player is written in case 1.

Similarly, a block of code related to two players for case 2.

The same logic executed using a switch statement can be written using if elseif.

The diagram below shows the use of if-else instead of the switch statement.

Languages like Python do not have switch statements for this reason.