Java / Java 21 Coding Standards Interview Questions
What is the difference between var and explicit typing under Java 21 style guides?
var and explicit typing produce identical bytecode and identical static type safety - the difference is purely about what the reader sees at the declaration site, not about behavior or performance.
| var | Explicit type |
| Type is inferred from the initializer at compile time. | Type is written out and enforced by the declaration itself. |
| Best when the right-hand side already makes the type obvious. | Best when the initializer alone does not reveal the type clearly. |
| Cannot be used for fields, parameters, or return types. | Usable everywhere a type is declared. |
Style guides frame the choice as a readability decision: use var when it shortens a verbose generic declaration without hiding meaning, such as var entries = new HashMap<String, List<Order>>(), and use the explicit type whenever inference would force the reader to trace back to a method signature to know what they are looking at.
More Related questions...