This came as a surprise: I am able to declare a variable with the name record
even though it now has become a keyword. Have a look at this:
public class Main {
static class Foo {
void bar() { System.out.println("Foo.bar"); }
}
record R (int a) {}
public static void main(String[] args) {
Foo record = new Foo();
record.bar();
R r = new R(5);
System.out.println(r);
}
}
When compiled and run with Java 17 this gives:
Foo.bar
R[a=5]
I had expected this to result in an error as is the case when trying to declare a variable named class
. As I know the Java guys, they are extremely careful not to break existing code, and so I think this might be a deliberate choice.
(You can't even declare a variable named const
because that one const
is a keyword in Java.)
We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.
Answer. Explanation: There are some words that you can't use in your Java programming because the keywords have a special meaning to the Java compiler and Java functions. If you attempt to use any of these reserved keywords as variable names in your application, you will see a compile time error.
You cannot use keywords as variable names. It's because keywords have predefined meanings.
The identifiers var and record are restricted identifiers because they are not allowed in some contexts.
Yes, this is legal because record
is not a reserved keyword; it is only
a contextual keyword.
The Java Language Specification has distinguished between contextual keywords (originally "restricted keywords" and later "restricted identifiers") and reserved keywords since Java 9, due to the introduction of several new keywords in that version. The rationale is given in JLS 9 (§3.9):
A further ten character sequences are restricted keywords:
open
,module
,requires
,transitive
,exports
,opens
,to
,uses
,provides
, andwith
. These character sequences are tokenized as keywords solely where they appear as terminals in theModuleDeclaration
andModuleDirective
productions (§7.7). They are tokenized as identifiers everywhere else, for compatibility with programs written prior to Java SE 9.
Essentially, Foo record = new Foo();
has to be legal in Java 17 because it was legal in earlier versions when record
wasn't any kind of keyword, and backwards compatibility is a very high priority for new versions of the Java language.
OK, while looking up const
in the JLS again, I saw that record
is a contextual keyword whereas const
is just a keyword. Contextual keywords are parsed according to context, and when the parser determines that it's not looking at a a record declaration, it will not complain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With