Java switch/case statement syntax

The switch statement in Java provides a convenient method for branching a program based on a number of conditionals. This tech-recipe describes the use of the Java switch statement.


The basic format of a switch statement in Java is as follows:

switch (expression) {
case cond1: code_block_1;
case cond2: code_block_2;
...
case condn: code_block_n;
default: code_block_default;
}

where expression is an integral expression (such as int, char, short, or byte, but not long). In each case statement within the switch statement, a comparison is made which is equivalent to if (expression == cond1). If the comparison evaluates to true, the code within the block is executed. The final default: line is analogous to a final else statement.

This arrangement is similar to a cascade of if/else if/else if statements but with one substantial difference. At the end of each code block, an optional break statement alters the flow through the switch statement. Without any break statements, all subsequent code blocks will be executed once a true evaulation is found. To make a switch statement behave just like an if/else if/else if statement, always put break statements at the end of code blocks. However, leaving out break statements can provide a capability very difficult to achieve with if statements.

For example, consider the following code:

public class TestSwitch {

public final static int TITANIUM = 0;
public final static int PLATINUM = 1;
public final static int GOLD = 2;
public final static int SILVER = 3;
public final static int TIN = 4;

public static void main(String[] args) {
System.out.println("Tin -----");
printGift(TIN);
System.out.println("Titanium -----");
printGift(TITANIUM);
}

public static void printGift(int serviceLevel) {
switch(serviceLevel) {
case TITANIUM: case PLATINUM:
System.out.println(" Free toaster");
case GOLD:
System.out.println(" Free stapler");
case SILVER: case TIN:
System.out.println(" Free staple remover");
break;
default:
System.out.println("No gift");
}
}
}

The example demonstrates break usage since any match will cause one or more println commands to output text but will not print the “No gift” line from the default code block. In addition, note that multiple case statements can be placed before each code block. Running this sample code results in the following output:

Tin -----
Free staple remover
Titanium -----
Free toaster
Free stapler
Free staple remover

The Conversation

Follow the reactions below and share your own thoughts.

27 Responses to “Java switch/case statement syntax”

  1. June 18, 2009 at 4:57 am, Irene said:

    Im a new learner of java. This example of switch case helped me to understand the syntax clearly. The program also provided more knowledge. I will visit this site whenever i get doubt.Thanks. Good work.

    Reply

  2. July 17, 2009 at 9:37 am, Akila said:

    Inside the switch case program is it possible to access another program? how?

    Reply

  3. August 02, 2009 at 3:25 pm, Anonymous said:

    import java.io.*;
    import java.net.*;
    public class SvowelDPS
    {
    public static void main(String args[]) throws Exception
    {
    DatagramSocket ds=new DatagramSocket(40000);
    byte rb[]=new byte[100];
    System.out.println(“Connection”);

    DatagramPacket dp=new DatagramPacket(rb,rb.length);
    ds.receive(dp);
    System.out.println(“Receive Data:”+new String(dp.getData()));
    String str=new String(dp.getData());
    String res=”";
    str=str.trim();
    switch(str) //error on this point.How can i do?
    {
    case “a”:
    res=(“Vowel”);
    break;
    case “A”:
    res=(“Vowel”);
    break;
    case “e”:
    res=(“Vowel”);
    break;
    case “E”:
    res=(“Vowel”);
    break;
    case “i”:
    res=(“Vowel”);
    break;
    case “I”:
    res=(“Vowel”);
    break;
    case “o”:
    res=(“Vowel”);
    break;
    case “O”:
    res=(“Vowel”);
    break;
    case “U”:
    res=(“Vowel”);
    break;
    case “o”:
    res=(“Vowel”);
    break;
    default:
    res=(“Not Vowel”);
    break;
    }

    InetAddress cipadd=dp.getAddress();
    int cport=dp.getPort();
    byte sb[]=new byte[100];
    sb=res.getBytes();
    DatagramPacket dpsend=new DatagramPacket(sb,sb.length,cipadd,cport);
    ds.send(dpsend);
    System.out.println(“Data send”) ;
    }

    }

    Reply

    • August 11, 2009 at 1:55 am, Anonymous said:

      You cannot use strings on Swithc, you can only use int. So, it would be a better idea to capture the lettes ascii code and evaluate your switch accordingly.

      Reply

    • September 08, 2009 at 9:40 pm, mohd said:

      since you are using characters try using ‘ ‘ (Single quotes) instead of using ” ” double quotes

      Reply

    • September 10, 2010 at 4:45 pm, justAsking said:

      is if else if statement inside a switch statement possible?

      Reply

      • March 15, 2013 at 4:28 am, bayram said:

        yes ıts possıble !

        Reply

  4. December 27, 2009 at 8:53 pm, McTOM said:

    Very good piece of knowledge. Exactly what i was looking for. Thanks!

    Reply

  5. January 18, 2010 at 6:36 pm, Anonymous said:

    this is all bulshit i failed my test cuz of this..i had totaly rong stuf.

    F******* u

    Reply

  6. January 18, 2010 at 6:37 pm, Anonymous said:

    f*** * m*** f***

    Reply

    • September 10, 2010 at 4:44 pm, justAsking said:

      is if else if statement inside a switch statement possible?

      Reply

      • October 06, 2010 at 8:01 pm, Papablopo said:

        yes

        switch (int){
        case 1:
        if (x = y) {
        class();
        }
        case 2:
        if (x = y) {
        class2();
        }
        default:
        class3();
        }

        Reply

  7. October 23, 2010 at 5:43 pm, sherral said:

    well i need help well m in 10 aand i hv project in computer to make software type programs..
    so i wanted to knw tht whether i can insert a program related to one of the options in the case???

    Reply

  8. October 24, 2010 at 5:33 pm, jose said:

    it is possible to make a loop between cases?

    Reply

  9. November 12, 2010 at 7:35 pm, kiabaman said:

    can someone tell me how to make the “case “#” ” have more than one character in the ‘ ‘?

    Reply

    • February 22, 2011 at 12:54 am, The_Lugdog said:

      i dont know

      Reply

  10. December 05, 2010 at 3:12 pm, Student said:

    i have the same question as kiabaman…

    Reply

  11. January 13, 2011 at 6:18 pm, Sajmmon said:

    If you need to switch over a value that is a string you can embed it into an Enum:

    public class Example{
    enum Values { a, b, c }
    public static void main(String[] args) {
    Values v = Values.a;

    switch() {
    case a:
    //TODO
    break;
    case b:
    //TODO
    break;
    case c:
    //TODO
    break;
    }
    }
    }

    Regards

    Reply

  12. January 18, 2011 at 5:20 pm, Ashish Narola Rajkot said:

    can i use multiple choice in case of SELECT……CASE statement ? i.e.

    select (expression)
    {
    case “a” or “A”:
    system.println(“vovel”);
    break;
    case “a” or “A”:
    system.println(“vovel”);
    break;

    case “e” or “E”:
    system.println(“vovel”);
    break;

    default:
    system.println(“Ashish you r wrong.”);

    }

    Reply

  13. June 21, 2011 at 6:51 am, Nadzirah_orangeleo said:

    import java.util.Scanner;public class switchDemo {
          public static void main(String[] args) {
            Scanner inputDevice = new Scanner(System.in);        System.out.println(“Enter a number for a month”);        int iUserInput = inputDevice.nextInt();
                       switch (iUserInput) {            case 1:  System.out.println ( “January” );     break;            case 2:  System.out.println (“February”);      break;            case 3:  System.out.println (“March”);         break;            case 4:  System.out.println (“April”);         break;            case 5:  System.out.println (“May”);           break;            case 6:  System.out.println (“June”);          break;            case 7:  System.out.println (“July”);          break;            case 8:  System.out.println (“August”);        break;            case 9:  System.out.println (“September”);     break;            case 10: System.out.println (“October”);       break;            case 11: System.out.println (“November”);      break;            case 12: System.out.println (“December”);      break;            default: System.out.println (“Invalid month”); break;                    }}}
     

    Reply

    • July 16, 2011 at 5:29 am, man-man said:

      IS it need to Use Breaks in dEfault?

      Reply

    • July 16, 2011 at 5:29 am, man-man said:

      IS it need to Use Breaks in dEfault?

      Reply

  14. July 06, 2011 at 1:40 pm, Shimmer_boy3 said:

    hmm.. h0w ab0ut   

    char a;
        a = (char)System.in.read();
            switch (a){ 
       case a:
            System.out.println(“Less 10% :” + (x-x*0.10));
            break;
       case b:
            System.out.println(“Penalty 5% :” + (x+x*0.05+x));
            break;
       case c:
            System.out.println(“Penalty 10% :”+ (x+x*0.10));
            break;

    what express|0n sh0uld | use??? s0 |t can read the char? 0r case a case b case c???

    Reply

  15. December 13, 2011 at 3:27 am, Shan Tabuena said:

    In arrays statement how i going to do to make the out reverse?
    for example ABC
    the Output is CBD.. thank you.

    Reply

  16. January 16, 2012 at 1:25 pm, Reterio said:

    You do not need to use break in DEFAULT,

    the best way to understand break is not to use it, eg

    switch(var){
    case a:
    case b:
    case c:
    // do something
    break;
    case d:
    // do something else
    }

    which means to do sth. in case of any of a,b,c but not d

    Reply

  17. February 28, 2012 at 3:57 pm, Biurowe said:

    You dont need to use BREAK in DEFAULT, its function in this location is neutral

    Reply

  18. November 30, 2012 at 3:01 am, jagadeeshsimhani said:

    if (rowData[0].getContents().length() != 0) { // the first date column must not null
    for (int j = 0; j < columnCount; j++) {
    switch (j) {
    case 0:
    System.out.println("Employee Id:" + rowData[j].getContents());
    case 1:
    System.out.println("Employee Name:" + rowData[j].getContents());
    case 2:
    System.out.println("Employee Designation:" + rowData[j].getContents());
    default:
    break;
    } BUT I WANT to collect all 3 cases data and pass that data to method and call that method…store into DB…..is there any way ……..

    Reply

Leave a Reply