We all use switches regularly in our lives. Yes, I am talking about electrical switches we use for our lights and fans.

As you see from the below picture, each switch is assigned to operate for particular electrical equipment.

For example, in the picture, the first switch is for fan, next for light and so on.

Thus, we can see that each switch can activate/deactivate only 1 item.

Java Switch Case Tutorial

What is Switch Case in Java?

Similarly, switch in java is a type of conditional statement that activates only the matching condition out of the given input.

Let us consider the example of a program where the user gives input as a numeric value (only 1 digit in this example) and the output should be the number in words.

The integer variable iSwitch ,is the input for the switch to work.

The various available options (read cases) are then written as case <value>alongwith a colon “:”

This will then have the statement to be executed if the case and the input to the switch match.

Java Switch Example

class SwitchBoard{
 public static void main(String args[]){
   int iSwitch=4;
     case 0:

     case 1:

     case 2:

     case 3:

     case 4:

     System.out.println("Not in the list");

Now what are those 2 words break and default lying out there do?

  • The first one “break” – will simply break out from the switch block once a condition is satisfied.
  • “Default” – This will be executed in case none of the conditions match the given input.

In the given example these are simple print statements, however they can also refer to more complex situations like calling a method etc.

What if you do not provide a break?

In case the break is not provided, it will execute the matching conditions as well as the default condition. Your logic will go haywire if that occurs.

I will leave it to the users to experiment without using break.

Java Switch statement:

  • As a standard programming logic, it can simply be achieved by using if…else conditions, but then it will not be optimized for good programming practicenor does the code look readable.

  • In programs involving more complex cases, scenarios will not be so simple and would require calling several methods.Switch solves this problem and avoids several nested if…else statements.Also, while using if….else, it is recommended to use the most highly expected condition to be on top and then go ahead in a nested manner.

  • Some benchmarking tests have proven that in java case of high number of iterations, the switch is faster as compared to if….else statements.

Points to Note

  • There is no limit on the number of case java you can have.
  • Switch java can take input only as integers or characters.
  • The latest version of Java8, also introduces the much awaited support for java switch strings statement.

So now go ahead and wire your own switch board!!