The switch statement for the Java basic syntax

Source: Internet
Author: User
Tags case statement

A switch statement consists of a control expression and multiple case labels.

The types supported by the switch control expressions are byte, short, char, int, enum (Java 5), String (Java 7).

The Switch-case statement can be fully interoperable with the If-else statement, but generally, the Switch-case statement executes more efficiently.

Default is executed when the current switch cannot find a matching case. Default is not a must.

Once the case is matched, the subsequent program code is executed sequentially, regardless of whether the following case matches until abreak is encountered.

1. Examples of enum types:
1  Public classTestswitch {2  3     Static enumE {4 A, B, C, D5     }6  7      Public Static voidMain (String args[]) {8E e =e.b;9         Switch(e) {Ten          CaseA: OneSystem.out.println ("A"); A              Break; -          CaseB: -System.out.println ("B"); the              Break; -          CaseC: -System.out.println ("C"); -              Break; +          CaseD: -System.out.println ("D"); +              Break; A         default: atSYSTEM.OUT.PRINTLN (0); -         } -     } -}
2. The use of break statements: output the number of days of a month in a given year
int year = 2018;
intMonth = 8;intDay = 0;Switch(month) { Case1: Case3: Case5: Case7: Case8: Case10: Case12: Day= 31; Break; Case2: Day= 28; Break; Case4: Case6: Case9: Case11: Day= 30; Break;} System.out.println (day);

The switch statement for the Java basic syntax

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.