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 recipe describes the use of the Java switch statement.
The basic format of a switch statement in Java is:
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 (like 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











Irene said on June 18, 2009
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 said on July 17, 2009
Inside the switch case program is it possible to access another program? how?
Anonymous said on August 2, 2009
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 said on August 11, 2009
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 said on September 8, 2009
since you are using characters try using ‘ ‘ (Single quotes) instead of using ” ” double quotes
McTOM said on December 27, 2009
Very good piece of knowledge. Exactly what i was looking for. Thanks!
Anonymous said on January 18, 2010
this is all bulshit i failed my test cuz of this..i had totaly rong stuf.
F******* u
Anonymous said on January 18, 2010
f*** * m*** f***
justAsking said on September 10, 2010
is if else if statement inside a switch statement possible?
justAsking said on September 10, 2010
is if else if statement inside a switch statement possible?
Papablopo said on October 6, 2010
yes
switch (int){
case 1:
if (x = y) {
class();
}
case 2:
if (x = y) {
class2();
}
default:
class3();
}
sherral said on October 23, 2010
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 said on October 24, 2010
it is possible to make a loop between cases?
kiabaman said on November 12, 2010
can someone tell me how to make the “case “#” ” have more than one character in the ‘ ‘?
Student said on December 5, 2010
i have the same question as kiabaman…
Sajmmon said on January 13, 2011
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 said on January 18, 2011
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.”);
}
The_Lugdog said on February 22, 2011
i dont know
Nadzirah_orangeleo said on June 21, 2011
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; }}}
Shimmer_boy3 said on July 6, 2011
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???
man-man said on July 16, 2011
IS it need to Use Breaks in dEfault?
man-man said on July 16, 2011
IS it need to Use Breaks in dEfault?
Shan Tabuena said on December 13, 2011
In arrays statement how i going to do to make the out reverse?
for example ABC
the Output is CBD.. thank you.
Reterio said on January 16, 2012
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