Java basics 2: break keywords, java Basics

Source: Internet
Author: User

Java basics 2: break keywords, java Basics

The break in Java is generally used to jump out of a switch or loop.

Do not go into details when jumping out of the switch.

The break Jump Out Loop usually jumps out of the current loop.

If you need to jump out of a multi-tier loop, you can add a label after the break, and then mark the label before you need to jump out of the layer loop. This usage is similar to a goto statement.

This may not be very clear. You can see the following code at a glance.

public class Lesson03_1 {    public static void main(String[] args) {        Lesson03_1 l31 = new Lesson03_1();        l31.go();        System.exit(0);    }    public void go() {        String o = "";        z: for (int x = 0; x < 4; x++) {            zz: for (int y = 0; y < 2; y++) {                for (int k = 0; k < 5; k++) {                    if (x == 1)                        break;                    if (x == 2 && y == 1)                        break zz;                    o = o + x + y;                }            }        }        System.out.print(o);    }}

When it is executed to break;, it is to jump out of the loop at the last layer and execute the zz layer.

When the break zz; is executed, the zz loop exists and the layer z is executed.

※※In fact, tags can be applied to any statement, or even to the if statement or block statement, as shown below:

public static void main(String[] args) {    lable:    {        System.out.println("haha");        if(true) break lable;        System.out.println("gaga");    }    System.out.println("heihei");}

Print result:

hahaheihei

Visible System. out. println ("gaga"); not executed

※※A break statement is similar to a goto statement and is not recommended as a goto statement.

※※The break statement can only jump out of the statement block.

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.