Java Switch-Case Statement with Example

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 a 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 of 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;
   switch(iSwitch){
     case 0:
     System.out.println("ZERO");
     break;

     case 1:
     System.out.println("ONE");
     break;

     case 2:
     System.out.println("TWO");
     break;

     case 3:
     System.out.println("THREE");
     break;

     case 4:
     System.out.println("FOUR");
     break;

     default:
     System.out.println("Not in the list");
     break;
 }
}
}

Output:

FOUR

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

In the given an 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 a break.

Java Switch statement:

Points to Note

So now go ahead and wire your own switchboard!!

 

YOU MIGHT LIKE: