Exams Knowledge Hub

MCQs for Competitive Exams, School & College Exams

Module: | Core Architecture, Basics & Control Flow

Q13: Consider the following statements regarding Local Variable Type Inference (LVTI) and the 'var' keyword:

1. The 'var' keyword, introduced in Java 10, enables the compiler to automatically infer the data type of a local variable by analyzing the value assigned to it on the right-hand side.
2. A developer can successfully utilize the 'var' keyword to declare uninitialized local variables, as the compiler will temporarily assign a default null state.
3. The 'var' keyword can only be applied to local variables inside methods or blocks and is strictly prohibited for declaring class-level instance variables or method return types.

Which of the above statements is/are correct?
A
Only 1 and 2
B
Only 1 and 3
C
Only 2 and 3
D
1, 2, and 3
✅ Correct Answer: B
🎯 Quick Answer:
The correct combination is 1 and 3. Statement 2 is incorrect because the 'var' keyword fundamentally requires immediate initialization at the time of declaration. Without an initial value, the compiler has no reference data to infer the type from, resulting in a compile-time error.
Concept Definition: Local Variable Type Inference (LVTI) is a feature that reduces boilerplate code by allowing developers to omit the explicit type declaration for a variable, delegating the type deduction to the Java compiler.
Structural Breakdown: Instead of writing 'HashMap\ map = new HashMap\();', a developer can concisely write 'var map = new HashMap\();'. Historical/Related Context: Java has historically been heavily criticized for being overly verbose compared to modern languages like Python or JavaScript.
The implementation of 'var' in Java 10 (via JEP 286) was a major shift to improve code readability and developer productivity without sacrificing Java's strict static type safety.
Causal Reasoning: The restriction of 'var' to local scopes (Statement 3) exists to maintain global code clarity.
If instance variables or method return types used 'var', it would force developers reading the API or class structure to hunt down initialization code just to understand the fundamental contract of the class, severely degrading maintainability.