Java Switch-case

Source: Internet
Author: User

First, the principle is to explain the problem:

switch (expression)
{
case constant Expression 1: statement 1;
....
Case constant Expression 2: statement 2;
Default: statement;
}
1.default is that if you do not have a matching case, default is not required.
The statement after 2.case can be used without curly braces.

the judging condition of 3.switch statement can accept int,byte,char,short,string,enum other types cannot be accepted.

4. Once the case is matched, the subsequent program code is executed sequentially, regardless of whether the following case matches, until a break is encountered, which allows several case to execute a unified statement.

Principle of the principle, here are a few easy to confuse examples.

1. Standard type (the break statement is followed by case)
int i=3;
Switch (i)
{
Case 1:
SYSTEM.OUT.PRINTLN (1);
Break
Case 2:
SYSTEM.OUT.PRINTLN (2);
Break
Case 3:
SYSTEM.OUT.PRINTLN (3);
Break
Default
SYSTEM.OUT.PRINTLN ("Default");
Break
}
Output Result:
3
2. Special Type 1 (not completely break statement, can complete some special applications)
int year=2005;
int month=3;
int day;
Switch (month)
{
Case 1:
Case 3:
Case 5:
Case 7:
Case 8:
Case 10:
Case 12:
day=31;
Break
Case 2:
day=28;
Break
Case 4:
Case 6:
Case 9:
Case 11:
day=30;
Break
}
Here day=31;
3. Special type 2 (default position)
int i=1;
Switch (i)
{
Case 1:
SYSTEM.OUT.PRINTLN (1);
Default
SYSTEM.OUT.PRINTLN ("Default");
Case 2:
SYSTEM.OUT.PRINTLN (2);
Break
Case 3:
SYSTEM.OUT.PRINTLN (3);
Break
}
Output Result:
1
Default
2

Java Switch-case

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.