Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Language Basics
Variables
Primitive Data Types
Arrays
Summary of Variables
Questions and Exercises
Operators
Assignment, Arithmetic, and Unary Operators
Equality, Relational, and Conditional Operators
Bitwise and Bit Shift Operators
Summary of Operators
Questions and Exercises
Expressions, Statements, and Blocks
Questions and Exercises
Control Flow Statements
The if-then and if-then-else Statements
The switch Statement
The while and do-while Statements
The for Statement
Branching Statements
Summary of Control Flow Statements
Questions and Exercises
Trail: Learning the Java Language
Lesson: Language Basics
Section: Control Flow Statements
Home Page >Learning the Java Language >Language Basics
« Previous • Trail • Next »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

The switch Statement

Unlikeif-then andif-then-else statements, theswitch statement can have a number of possible execution paths. Aswitch works with thebyte,short,char, andint primitive data types. It also works withenumerated types (discussed inEnum Types), theString class, and a few special classes that wrap certain primitive types:Character,Byte,Short, andInteger (discussed inNumbers and Strings).

The following code example,SwitchDemo, declares anint namedmonth whose value represents a month. The code displays the name of the month, based on the value ofmonth, using theswitch statement.

public class SwitchDemo {    public static void main(String[] args) {        int month = 8;        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);    }}

In this case,August is printed to standard output.

The body of aswitch statement is known as aswitch block. A statement in theswitch block can be labeled with one or morecase ordefault labels. Theswitch statement evaluates its expression, then executes all statements that follow the matchingcase label.

You could also display the name of the month withif-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 useif-then-else statements or aswitch statement is based on readability and the expression that the statement is testing. Anif-then-else statement can test expressions based on ranges of values or conditions, whereas aswitch statement tests expressions based only on a single integer, enumerated value, orString object.

Another point of interest is thebreak statement. Eachbreak statement terminates the enclosingswitch statement. Control flow continues with the first statement following theswitch block. Thebreak statements are necessary because without them, statements inswitch blocksfall through: All statements after the matchingcase label are executed in sequence, regardless of the expression of subsequentcase labels, until abreak statement is encountered. The programSwitchDemoFallThrough shows statements in aswitch block that fall through. The program displays the month corresponding to the integermonth and the months that follow in the year:

public class SwitchDemoFallThrough {    public static void main(String[] args) {        java.util.ArrayList<String> futureMonths =            new java.util.ArrayList<String>();        int month = 8;        switch (month) {            case 1:  futureMonths.add("January");            case 2:  futureMonths.add("February");            case 3:  futureMonths.add("March");            case 4:  futureMonths.add("April");            case 5:  futureMonths.add("May");            case 6:  futureMonths.add("June");            case 7:  futureMonths.add("July");            case 8:  futureMonths.add("August");            case 9:  futureMonths.add("September");            case 10: futureMonths.add("October");            case 11: futureMonths.add("November");            case 12: futureMonths.add("December");                     break;            default: break;        }        if (futureMonths.isEmpty()) {            System.out.println("Invalid month number");        } else {            for (String monthName : futureMonths) {               System.out.println(monthName);            }        }    }}

This is the output from the code:

AugustSeptemberOctoberNovemberDecember

Technically, the finalbreak is not required because flow falls out of theswitch statement. Using abreak is recommended so that modifying the code is easier and less error prone. Thedefault section handles all values that are not explicitly handled by one of thecase sections.

The following code example,SwitchDemo2, shows how a statement can have multiplecase labels. The code example calculates the number of days in a particular month:

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 code:

Number of Days = 29

Using Strings in switch Statements

In Java SE 7 and later, you can use aString object in theswitch statement's expression. The following code example,StringSwitchDemo, displays the number of the month based on the value of theString namedmonth:

public class StringSwitchDemo {    public static int getMonthNumber(String month) {        int monthNumber = 0;        if (month == null) {            return monthNumber;        }        switch (month.toLowerCase()) {            case "january":                monthNumber = 1;                break;            case "february":                monthNumber = 2;                break;            case "march":                monthNumber = 3;                break;            case "april":                monthNumber = 4;                break;            case "may":                monthNumber = 5;                break;            case "june":                monthNumber = 6;                break;            case "july":                monthNumber = 7;                break;            case "august":                monthNumber = 8;                break;            case "september":                monthNumber = 9;                break;            case "october":                monthNumber = 10;                break;            case "november":                monthNumber = 11;                break;            case "december":                monthNumber = 12;                break;            default:                 monthNumber = 0;                break;        }        return monthNumber;    }    public static void main(String[] args) {        String month = "August";        int returnedMonthNumber =            StringSwitchDemo.getMonthNumber(month);        if (returnedMonthNumber == 0) {            System.out.println("Invalid month");        } else {            System.out.println(returnedMonthNumber);        }    }}

The output from this code is8.

TheString in theswitch expression is compared with the expressions associated with eachcase label as if theString.equals method were being used. In order for theStringSwitchDemo example to accept any month regardless of case,month is converted to lowercase (with thetoLowerCase method), and all the strings associated with thecase labels are in lowercase.

Note: This example checks if the expression in theswitch statement isnull. Ensure that the expression in anyswitch statement is not null to prevent aNullPointerException from being thrown.

« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

Previous page: The if-then and if-then-else Statements
Next page: The while and do-while Statements

[8]ページ先頭

©2009-2025 Movatter.jp