The switch Statement example in Java

By: Kamini Emailed: 1697 times Printed: 2202 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer.

The following program, SwitchDemo, declares an int named month whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using the switch statement.

 

class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        switch (month) {
            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;
        }
    }
}

In this case, "August" is printed to standard output.

The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case.

Of course, you could also implement the same thing with if-then-else statements:

int month = 8;
if (month == 1) {
    System.out.println("January");
} else if (month == 2) {
    System.out.println("February");
}
. . . // and so on

Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call. You can decide which one to use based on readability and other factors. An if-then-else statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value.

Another point of interest is the break statement after each case. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements. The following program, SwitchDemo2, illustrates why it might be useful to have case statements fall through:

class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}

This is the output from the program.

    Number of Days = 29

Technically, the final break is not required because flow would fall out of the switch statement anyway. However, we recommend using a break so that modifying the b is easier and less error-prone. The default section handles all values that aren't explicitly handled by one of the case sections.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(10)


1. View Comment

why it is( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) we can only only (year % 4 == 0) right, and also if u give year 100 or 200 is showing only 28days, thats wrong... if u write only (year % 4 == 0) this much it shows perfectly...

View Tutorial          By: Jai Shankar K at 2012-04-08 10:15:56
2. View Comment

@Jai Shankar K

I'm guessing you are not really that familiar with leap years. That's not to be unexpected, after all you're probably not over 113 years old, hell maybe you are not ever 13 years old. However the person who wrote this example knows that when a year is divisible by 100 (ie 500, 1600, 1700, 2000 etc) it may or may not be a leap year. If leap years were every 4 years, then over hundreds or years we would add too much time. Every 400 years our calendar would be off by an additional 3 days. To adjust for this, if a year is divisible by 100 and not by 400 then it is NOT a leap year. If the last two numbers are '00', then only years which are divisible by 400 are leap years. So, only the years 400, 800, 1200, 1600, and 2000 were leap years. 1500, 1700, 1800, and 1900 were not.
There are also leap seconds which are added every now and again for fine tuning.


View Tutorial          By: Nick Scroggs at 2013-03-26 01:44:04
3. View Comment

import java.util.Scanner;
public class SwitchDemo {
public static void main(String[] args) {

Scanner d=new Scanner(System.in);
int month=d.nextInt();
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}


View Tutorial          By: srinath at 2013-04-28 10:17:24
4. View Comment

its a big help!..thankz

View Tutorial          By: mezer at 2013-07-17 05:34:07
5. View Comment

How would you use a switch statement to determine if a number input by a user is positive or negative or zero? I can totally see how to do that with an if/else statement, but how about a switch statement?

View Tutorial          By: Shivak at 2013-09-27 01:48:41
6. View Comment

Write a program to input the number and use switch case to find?
1-largest digit.
2-minimum digit.
3- odd and even digit.


View Tutorial          By: abdulaziz at 2014-03-28 16:22:35
7. View Comment

I need to get the brief notes on this example
switch(variable)
{
case(1):something;
break;
case(23):something;
break;
default : something;
}


View Tutorial          By: Racchana Srini at 2014-07-29 07:50:22
8. View Comment

can for statement be used in a switch statement for the looping of digits obtain from a user

View Tutorial          By: Osei Quadwo at 2014-10-08 20:12:17
9. View Comment

I want to using swith with string...
How to use the string in switch case.
Please give me answer...


View Tutorial          By: anuj at 2015-03-04 18:22:29
10. View Comment

nice

View Tutorial          By: utkarsh at 2015-03-10 03:18:26

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Kamini
Importing the Certificate Reply from the CA example using keytool in Java
The switch Statement example in Java
Joins example in SQL
ERRNO.H Header File in C
XDoclet struts-config.xml in Struts
Macro Substitution using #define in C
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Do while Loops in C
Functions in C
Opening files for read and write in C++
Operator Precedence in C++
StringItem sample program in J2ME
AWT-based applications with a User Interface Window in Java
store() and load() example in Java
Stray or Dangling Pointers in C++

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
Student marks calculation program in Java
XML and Java - Parsing XML using Java Tutorial
append() in Java
How to use ArrayList in Java
Garbage collection and Finalize() method
Using StringTokenizer in Java
Abstract classes in Java
Increment and Decrement Operator
Read from a COM port using Java program
Count number of vowels, consonants and digits in a String in Java
Integer: byte, short, int, and long data types in Java
indexOf( ) and lastIndexOf( ) in Java
Using toLowerCase( ) and toUpperCase( ) in Java
The Basic Structure of a Simple Java program
Most Emailed Articles (in Java)
How to use ArrayList in Java
Write to a COM port using Java program
Read from a COM port using Java program
How to access instance from an inner class and accessing outer class variables in java
Data Types in Java
Tomcat and httpd configured in port 8080 and 80
Save/Write/Read image file from/to a database using Java program
Java program for changeable wrapper class
History of Java
Method Overloading (function overloading) in Java
Sample Java program shows how to write to COM port using Java.
Sample program to demonstrate the use of ActionListener
Introducing JavaScript.
Assigning Object Reference Variables
Bitwise Operator Assignments