Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysterious error when naming a variable "goto"? [closed]

Tags:

java

I tried to write some trivial code that concatenates two strings and prints them:

class A {
    public static void main(String[] args) {
        String goto = "jon skeet";
        System.out.println("the go-to guy for java questions is " + goto);
    }
}

But it gets all these errors:

$ javac A.java && java A
A.java:3: not a statement
        String goto = "jon skeet";
        ^
A.java:3: ';' expected
        String goto = "jon skeet";
              ^
A.java:4: illegal start of expression
        System.out.println("the go-to guy for java questions is " + goto);
                                                                    ^
A.java:4: ';' expected
        System.out.println("the go-to guy for java questions is " + goto);
                                                                        ^
4 errors

Why?

like image 237
Dog Avatar asked Nov 30 '25 11:11

Dog


2 Answers

goto is a reserved keyword in Java and cannot be used as a variable name, although it does not do anything.

Quote from the JLS 3.9:

50 character sequences, formed from ASCII letters, are reserved for use as keywords and cannot be used as identifiers (§3.8).

(goto is on this list)

The keywords const and goto are reserved, even though they are not currently used. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in programs.

like image 120
Adam Siemion Avatar answered Dec 03 '25 00:12

Adam Siemion


goto is a reserved word in Java although it is not used for anything.

like image 43
André Stannek Avatar answered Dec 03 '25 01:12

André Stannek