Switch to full style
General Java code examples
Post a reply

java switch example

Wed Oct 24, 2012 10:13 pm

How to use Java Switch?
Switch is a common keyword between Java and many other programming languages such as C++, PHP, PERL, C#, ASP, JavaScript and many others. Switch is used to replace a set of IF Conditions with Cases that you may have in your application logic. Switch uses Its input to select which cases to run. The switch input and cases' values should be from the same type. In java the input can be of type integers, characters, Enums and strings (Starting from JDK7). Following are some general hints about Java Switch:
  • Use the keyword switch to define any new switch statement.
  • The switch input is written between the two braces and it can be fixed or variable.
  • Java input can be only integers ( or any primitive type after casting to integer type), character, Enum, and String(JDK7).
  • Use case keyword to define any new condition(case).
  • If the switch input value got matched with a case value , this case value are going to be executed.
  • Duplicate cases are not allowed.
  • You have to use the break keyword at the end of each case to prevent the running the next case below the selected one.
  • default keyword can be use to define a general case executed in cases if not match found.
  • Default case is not mandatory to be defined.
  • The order of default case is not restricted to be at last, for instance it can be the first case and this will not affect the results.
  • It is correct syntax to declare a switch without any cases.
    Code:
    switch(1)
            {
                
            
    }
     

Switch On Integers


This part illustrates with examples the usage integer inputs to Java switch. Below is a code example for an integer variable switchX which is initialized with value equal "1"passed to switch statement:
Code:

 int switchX 
= 1;
        switch (switchX) {
             
            case 1
:
                System.out.println("output is 1");
                break;
            case 2:
                System.out.println("output is 2");
                break;
            case 3:
                System.out.println("output is 3");
                break;
            case 4:
                System.out.println("output is 4");
                break;
            case 5:
                System.out.println("output is 5");
                break;
           default:
                System.out.println(" no case found switchX");

        }
 

Here there this a match between case(1) and input value based on that the output of this code is :
Code:
output is 1

If you changed the place of default case from bottom to top as this:
Code:

 int switchX 
= 1;
        switch (switchX) {
              default:
                System.out.println(" no case found switchX");
            case 1:
                System.out.println("output is 1");
                break;
            case 2:
                System.out.println("output is 2");
                break;
            case 3:
                System.out.println("output is 3");
                break;
            case 4:
                System.out.println("output is 4");
                break;
            case 5:
                System.out.println("output is 5");
                break;
          

        
}
 

No changes will come to the output but If you removed the break keyword from case 1. The output will change because the next case (case2) is going to execute too. For instance :
Code:

  int switchX 
= 1;
        switch (switchX) {
             
            case 1
:
                System.out.println("output is 1");
             
            case 2
:
                System.out.println("output is 2");
                break;
            case 3:
                System.out.println("output is 3");
                break;
            case 4:
                System.out.println("output is 4");
                break;
            case 5:
                System.out.println("output is 5");
                break;
           default:
                System.out.println(" no case found switchX");

        }
 

The output is :
Code:
output is 1
output is 2

So, It is very important to determine where to add the break statements and when to ignore it. Now, what about input types such float,double and bye. As you may knew those datatypes can be converted to integer using casting concept. Are there any of these types could be used as switch input? The answer is pretty clear: "Yes". For example, at code below passing byte variable as switch input is implemented and compiled:
Code:


        byte byteA 
= 43;
        switch (byteA) {
            case 43:
                System.out.println("output is 43");
            case 44:
                System.out.println("output is 44");
                break;
            default:
                System.out.println(" no case found");
        }

 

The output is
Code:

output is 43
output is 44

The only limitation on byte switch input is the lose of precision. If you tried to use large integer cases for input of type bye It will not compile :
Code:

  byte byteA 
= 43;
        switch (byteA) {
            case 443:
                System.out.println("output is 443");
            case 424:
                System.out.println("output is 424");
                break;
            default:
                System.out.println(" no case found");
        }
 

Based on casting you can pass float data type as input to java switch statement:
Code:

   float x 
= 3.4f;

        switch ((int) x) {
            case (int) 3.2f:
                System.out.println("3.2 Grade");break;
            case (int) 4.0f:
                System.out.println("4 Grade");break;
        }
 

The output is :
Code:
3.2 Grade

Note that the default case is not mandatory to be part of your switch cases. You can also put your switch inside a for loop like this :
Code:

  
// switch on integer
        for (int x = 2; x <= 7; x++) {
            switch (x) {
                case 1:
                    System.out.println("X equals 1");
                    break;
                case 2:
                    System.out.println("X equals 2");
                    break;
                case 3:
                    System.out.println("X equals 3");
                    break;
                case 4:
                    System.out.println("X equals 4");
                    break;
                case 5:
                case 6:
                    System.out.println("X equals 6");
                    break;
                default:
                    System.out.println("No case of for number: " + x);
            }
        }
 

The output of this loop switch example is :
Code:
X equals 2
X equals 3
X equals 4
X equals 6
X equals 6
No case of for number: 7

Switch On Enum Values


In example below I apply java switch statement on a custom defined Enum named "Colors". This Enum has three string values "RED","GREEN" and "BLUE". Java switch works fine with Enums as follows:
Code:

public class SwitchExample 
{

    public enum Colors {

        RED, GREEN, BLUE;
    }

    public static void main(String[] args) {
         // Switch on enum
        Colors myColor = Colors.GREEN;

        switch (myColor) {
            case BLUE:
                System.out.println("Enum value equal BLUE");
                break;
            case RED:
                System.out.println("Enum value equal RED");
                break;
            case GREEN:
                System.out.println("Enum value equal GREEN");
                break;

        }

    }
}
 


The output of this snippet is :
Code:
Enum value equal GREEN

Switch on Character


Switch on character variable works like the other types by taking in mind that java switch on characters is "case sensitive":
Code:

       
// switch on character
        char color = 'R';
        switch (color) {

            case 'R':
                System.out.println("This is Red");
                break;
            case 'G':
                System.out.println("This is Green");
                break;
            case 'B':
                System.out.println("This is Blue");
                break;

        }
 

The output is :
Code:
This is Red

Switch on String


Starting at JDK7 It is possible to  apply switch mapping on strings' values as follows :
Code:

 String postalCode 
= "11232";
    

        switch 
(postalCode) {
            case "11123":
             System.out.print("Your city is x");
                break;
            case "33423":
               System.out.print("Your city is y");
                break;
            case "11232":
                System.out.print("Your city is z");
                break;
 

            default
:
                throw new IllegalArgumentException("Don't know your x");
        }
 

The output is :
Code:
Your city is z

Usually the default case is used to handle the unavailability of matches by throwing exceptions. This pattern is used regularly by experts software engineering to mange software logic unhandled cases.



Re: java switch example

Tue Jun 11, 2013 10:34 pm

updated.

Post a reply
  Related Posts  to : java switch example
 Java Matrices using a Switch Statement     -  
 Switch vs Hub     -  
 php switch     -  
 network switch     -  
 Use Switch with strings     -  
 JavaScript switch example     -  
 switch command for string value     -  
 switch keyword in c++ usage     -  
 restrictions on the values of each case of a switch     -  
 Hub-Switch-Router-Proxy-Firewall ?     -  

Topic Tags

Java Basics