Java switch statement (translated from Java tutorials)

Source: Internet
Author: User
Tags month name

From http://www.cnblogs.com/ggjucheng/archive/2012/12/16/2820839.html

English from http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

UnlikeIf-then andIf-then-else statement, the switch statement can have multiple possible execution paths. Switch works onByte,Short,Char,Int native type. It also applies to enumeration types, string classes, and several special native type packaging classes:Character,Byte,Short, AndInteger.

The followingCodeExample,Switchdemo: declares an int type named month. Its value indicates the month. The Code uses the switch statement to display the month name based on the value of month.

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, the outputAugust to standard output.

The body of the switch statement. It is known as a switch block. The switch block statement can mark one or more default labels. The switch statement calculates its expression and then executes all the Code following the corresponding case label.

Use the if-then-else statement to display the name of month:

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

Deciding when to use the if-then-Else and switch statements is the readability tested based on the expression statements.The if-then-else statement can test the range of the expression value and the conditional expression. The switch statement can only test the expression based on numbers, enumeration types, and string objects.

Another point of interest is the break statement. Each break statement can end the block closed by the switch statement. The control flow starts from the first statement of the switch block. The break statement is required. Without it, the statement of the switch block will blow off the code after the matching case label, it will be executed in order, regardless of the expression of the Case label following it until a break statement.ProgramSwitchdemofallthroughFailed to display the switch block statement. The program displays the month of a year based on the integer month:

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 ("CMDL"); 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 );}}}}

 

The code output is:

 
Augustseptemberoctobernovemberdecember

Technically, the last break statement is not mandatory because the control flow has left the switch statement. It is recommended to use break because it is easier to modify the code and reduce the number of common errors. If each value of the Case segment cannot be processed, the default segment will process all values.

The following code example,Switchdemo2, which shows that a statement can have multiple case labels. The code example calculates the number of days in a specific 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 );}}

 

The code output is:

 
Number of days = 29
Switch statement using strings

for Java 7 and later versions, you can use a String object in the expression of the switch statement. The following code example shows stringswitchdemo, which displays the integer of the month based on the name of the month:

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 "CMDL": 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 );}}}

Code output is 8.

String of the switch expression. Compare the expressions associated with each case tag,String. equalsWill be used. To makeThe stringswitchdemo example accepts the name of any month, regardless of case. Month is converted to lowercase (UseTolowercase Method), While the strings associated with the case tag are all in lower case.

Note:Example: Check whether the expression in the switch statement is null. Make sure that any expression in the switch statement is not null to avoid throwing an nullpointerexception.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.