Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Label

Java Examples - Label

Java Examples Java Examples

In Java, a label is an identifier used to mark a code block, usually used together with loop statements (such as for, while, do-while) and branching statements (such as if-else, switch).

The syntax of a label is to put an identifier before a code block, ending with a colon, for example:

labelName:

To jump out of the code block marked by a label, you can use a break or continue statement followed by the label.

The following example demonstrates how to use a label together with a break statement to jump out of the outer loop:

Main.java File

public

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

outerLoop

:

for

(

int

i

=

0

;

i

<

3

;

i

++

)

{

innerLoop

:

for

(

int

j

=

0

;

j

<

3

;

j

++

)

{

if

(

i

==

1

&&

j

==

1

)

{

break

outerLoop

;

//

Jump out of the outer loop

}

System

.

out

.

println

(

"

i:

"

i

"

, j:

"

j

)

;

}

}

}

}

In the above code, the outer loop variable i ranges from 0 to 2, and the inner loop variable j also ranges from 0 to 2. When i equals 1 and j equals 1, the statement break outerLoop; is executed, jumping out of the outer loop. Otherwise, the values of i and j for the current iteration are printed.

The output of the above code is:


i: 0, j: 0
i: 0, j: 1
i: 0, j: 2

The following example demonstrates how to use a label together with a continue statement to control the loop:

Example

public

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

outerLoop

:

for

(

int

i

=

0

;

i

<

3

;

i

++

)

{

innerLoop

:

for

(

int

j

=

0

;

j

<

3

;

j

++

)

{

if

(

i

==

1

&&

j

==

1

)

{

continue

outerLoop

;

//

Skip the current iteration of the outer loop

}

System

.

out

.

println

(

"

i:

"

i

"

, j:

"

j

)

;

}

}

}

}

In the above code, the outer loop variable i ranges from 0 to 2, and the inner loop variable j also ranges from 0 to 2. When i equals 1 and j equals 1, the statement continue outerLoop; is executed, skipping the current iteration of the outer loop. Otherwise, the values of i and j for the current iteration are printed.

The output of the above code is:

i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2

Java Examples Java Examples