Java / Java 21 Interview Questions
What is 'var' in Java and what are its limitations?
var (JEP 286, Java 10) introduces local variable type inference. The compiler infers the type from the initialiser on the right-hand side; you do not need to write the type explicitly. It is not a dynamic type — the variable is still strongly typed at compile time; var is just syntactic sugar.
// Without var
Map> scores = new HashMap>();
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
// With var — type inferred from the right-hand side
var scores = new HashMap>(); // Map>
var reader = new BufferedReader(new FileReader("file.txt")); // BufferedReader
// Works in for-loops
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Works with try-with-resources
try (var in = new FileInputStream("data.bin")) { ... }
// CANNOT be used:
// var x; // no initialiser — type unknown
// var x = null; // null has no type
// private var name; // instance/static fields
// public var foo() { } // return types
// void bar(var x) { } // method parameters
// var x = { 1, 2, 3 }; // array initialiser without explicit type In Java 11, var was extended to lambda parameters so you can add annotations: (var x, var y) -> x + y is equivalent to (x, y) -> x + y but allows (@NotNull var x, @NotNull var y) -> x + y.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
