Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java definitions: Label, Token

I wrote this:

(fitness>g.fitness) ? return 1 : return -1;

and received the following error:

Syntax error on tokens, label expected instead.

Can anyone explain what tokens and labels are in this context?

Edit: Thanks for fixing my code, but could you explain anyway what tokens and labels are, for future reference?

like image 819
Meir Avatar asked Mar 27 '26 22:03

Meir


2 Answers

Tokens are the individual characters and strings which have some kind of meaning.

Tokens, as defined in Chapter 3: Lexical Structure of The Java Language Specification, are:

identifiers (§3.8), keywords (§3.9), literals (§3.10), separators (§3.11), and operators (§3.12) of the syntactic grammar.

The tokens in the given line are:

"(", "fitness", ">", "g.fitness", ")", "?", "return", "1", ":", "return", "-1", ";"

(Whitespace also counts, but I've omitted them from the above.)


Labels in Java are used for control of flow in a program, and is an identifier, followed by a colon.

An example of a label would be hello:.

Labels are used in conjunction with continue and break statements, to specify which control structure to continue or break to.

There is more information on Labeled Statements in Section 14.7 of The Java Language Specification.


The problem here is with the return statement:

(fitness>g.fitness) ? return 1 : return -1;
                      ^^^^^^

There is a : immediately following the return 1, which makes the compiler think that there is supposed to be a label there.

However, the return 1 is a statement in itself, therefore, there is no label identifier there, so the compiler is complaining that it was expecting an label, but it was not able to find a properly formed label.

(fitness>g.fitness) ?  return 1   :   return -1;
                       ^^^^^^^^   ^
                      statement   label without an identifier
like image 162
coobird Avatar answered Mar 30 '26 11:03

coobird


Return is a statement and ?: needs expressions and so it is not accepted.

return (fitness > g.fitness) ? 1 : -1;

is probably what you want.

When parsing the code is first split so that it is easier to understand, these units are called tokens. I guess label refers to one language construct that happens to be the first possible one in a statement.

To understand how the parser decides to give that error message would require digging into the parser. Giving good error messages from parser is not trivial.

like image 35
iny Avatar answered Mar 30 '26 12:03

iny