Java 10中var究竟属于哪种类型的标记?
Great question! Let's dive into this key detail from Heinz Kabutz's 255th newsletter focused on Java 10's local variable type inference:
var vs. Reserved Words varisn’t a reserved keyword in Java 10
Here’s the critical distinction: you can usevaras an identifier (like a variable name), but true reserved words such asassertdon’t allow this. For example:- Valid code (no compilation issues):
int var = 10; // Works perfectly in Java 10+ - Invalid code (throws a compile error):
var assert = 2; // Fails because `assert` is a reserved word
- Valid code (no compilation issues):
This design choice is a win for backward compatibility
The newsletter emphasizes that this was an intentional, positive decision. Any pre-Java 10 code that usedvaras an identifier (variable name, method parameter, etc.) will still compile smoothly in Java 10 and later versions. You won’t need to refactor those old identifiers just to upgrade your JDK!
内容的提问来源于stack exchange,提问作者fps

