Search code examples
javatokendefinitions

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?


Solution

  • 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