Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it allowed to label almost every statement in Java?

Tags:

java

I understand that the main purpose of labels is to use them with break and continue to alter the usual behaviour of the loop. But it's possible to label every statement that is not a declaration.

int j = 0;
LABEL1: j++;
LABEL2: for (int i = 0; i < 4 ; i++) {
    if (i == 3) break LABEL2;
}

Is there any purpose to labels like LABEL1 since it's not allowed to break LABEL1?

like image 339
jmlup Avatar asked Jan 31 '14 15:01

jmlup


People also ask

What is the use of labels in Java?

A Label object is a component for placing text in a container. A label displays a single line of read-only text. The text can be changed by the application, but a user cannot edit it directly.

Should you use labels in Java?

Yes, you should avoid using label unless there's a specific reason to use them (the example of it simplifying implementation of an algorithm is pertinent).

What is label statement in Java?

What is a labeled loop in Java? A label is a valid variable name that denotes the name of the loop to where the control of execution should jump. To label a loop, place the label before the loop with a colon at the end.


1 Answers

An early unreleased version of java used to have GOTO. In order to jump to any statement with GOTO, you have to be able to label it.

Then at some point James Gosling decided that it wasn't a good feature and ripped it out. This involved grepping through all java code that existed at the time and rewriting any GOTO usage; there were 13 uses. (Source: youtube video)

So, like GOTO still being a reserved word, it's a remnant of GOTO support.

like image 128
Wim Coenen Avatar answered Nov 14 '22 21:11

Wim Coenen