Warning: Invalid argument supplied for foreach() in /home/techrecipes/public_html/wp-content/themes/techrecipes/header.php on line 77

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.

  • Irene

    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.

  • Akila

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

  • Anonymous

    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”) ;
    }

    }

    • Anonymous

      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.

    • mohd

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

    • justAsking

      is if else if statement inside a switch statement possible?

      • bayram

        yes ıts possıble !

  • McTOM

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

  • Anonymous

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

    F******* u

  • Anonymous

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

    • justAsking

      is if else if statement inside a switch statement possible?

      • Papablopo

        yes

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

  • sherral

    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???

  • jose

    it is possible to make a loop between cases?

  • kiabaman

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

    • The_Lugdog

      i dont know

  • Student

    i have the same question as kiabaman…

  • http://www.ipipan.eu/~sch/ Sajmmon

    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

  • Ashish Narola Rajkot

    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.”);

    }

  • Nadzirah_orangeleo

    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;                    }}}
     

    • man-man

      IS it need to Use Breaks in dEfault?

    • man-man

      IS it need to Use Breaks in dEfault?

  • Shimmer_boy3

    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???

  • Shan Tabuena

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

  • http://www.reterio.com Reterio

    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

  • http://www.wuteh.com.pl Biurowe

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

  • jagadeeshsimhani

    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 ……..