Java basic syntax Learning (1) switch... case

Source: Internet
Author: User
Tags case statement

Switch... standard syntax of case

1 switch (variable to be selected) 2 {3 case value 1: Statement 1; 4 break; 5 case value 2: Statement 2; 6 break; 7 ....... 8 case value n: Statement n; 9 break; 10 default: Statement n + 1; 11 break; 12}

 

Switch... case is a convenient choice structure, but when using the switch, if the break is not written, some undiscoverable errors will occur.

If we do not write a break after writing a case statement, we will continue to execute the following statement in the case after executing this case statement until it ends when it encounters break or right braces.

In the example below, I omit a case, and the subsequent statement will be executed even if the condition is not met.

1 class Demo 2 {3 public static void main (String [] args) 4 {5 int a = 2; 6 switch (a) 7 {8 case 1: System. out. println ("case 1"); 9 break; 10 case 2: System. out. println ("case 2"); 11 // break; 12 case 3: System. out. println ("case 3"); 13 break; 14 default: System. out. println ("others"); 15 break; 16} 17} 18}

The execution result is as follows:

 

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.