Switch-case statements in Java

Source: Internet
Author: User
Tags case statement constant expression

The Switch-case statement in Process Control has always been a weakness of mine.

Whenever the exam or interview written test, always confused, I think this should be my foundation is too poor reason!

In order to completely solve this problem, we have to spend a little effort!

First of all, explain the problem from the principle:

switch (expression)

{Case constant Expression 1: statement 1;

....

Case constant Expression 2: statement 2;

Default: statement; }

1.default is to execute it without a match, and default is not necessary.

The statement after 2.case can be without curly braces.

The judgment condition of the 3.switch statement can accept Int,byte,char,short and cannot accept other types.

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

Principle, the following is a few confusing examples.

1. Standard type (there are break statements behind 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 results:

3

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.