user3184996
user3184996

Reputation: 31

What does the keyword loop in Java do?

public class Test 
{
        public void add(int a) 
        {
            loop: for (int i = 1; i < 3; i++)
            {
                    for (int j = 1; j < 3; j++) 
                    {
                        if (a == 5) 
                        {
                        break loop;
                        }
                        System.out.println(i * j);
                    }
            }
        }

        public static void main(String[] str)
        {
            Test t=new Test();
            t.add(4);s
        }
}

Upvotes: 0

Views: 302

Answers (4)

Mohan Singh
Mohan Singh

Reputation: 883

Mate,

loop is not any keyword in java. Its a label. Label are always used with break and continue to transfer the control flow.

Upvotes: 0

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

It's a shortcut for terminating both nested loops. Citing the Branching Statements page from Java Tutorial:

The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

and

An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.

It's not a keyword, it's a label you choose. Just mark the external loop with labelName: .... Then, you can nest loops and exit from them all by calling break labelName;:

yourLabelName: for(int i = 0; i < 3; ++i) {
    for (int j = 0; j < 7; ++j) {
        break yourLabelName;
    }
}
// After calling break yourLabelName, you will end up here 

In your case, when a == 5, then both loops are exited and the add() method terminates (returns).

Upvotes: 1

user2672373
user2672373

Reputation:

Its a label Syntax

label strLabel:
//Labeled block of statements

It is possible to specify labels with break and continue

Upvotes: 0

Qadir Hussain
Qadir Hussain

Reputation: 1263

First of all this code will not compile as there is an s present in your code. t.add(4);s. Remove s. After removing s your code output will be 1 2 2 4. And loop is not a keyword but it is label expression in Java

Upvotes: 0

Related Questions