1. Valid Use Cases of var
var is alocal variable type inferencefeature.
The compilerinfers the type from the assigned value.
Example of valid use:
java
var a = 10; // Type inferred as int
var str = "Hello"; // Type inferred as String
2. Analyzing the Given Statements
Statement
Valid/Invalid
Reason
var a = 1;
Valid
Type inferred as int.
var b = 2, c = 3.0;
❌Invalid
var doesnot allow multiple declarationsin one statement.
var d[] = new int[4];
❌Invalid
Array brackets []are not allowedwith var.
var e;
❌Invalid
varrequires an initializer(cannot be declared without assignment).
var f = { 6 };
❌Invalid
{ 6 } is anarray initializer, which must have an explicit type.
var h = (g = 7);
Valid
g is assigned 7, and h gets its value.
Thus, the correct answers are:B, C, D, E
References:
Java SE 21 - Local Variable Type Inference (var)
Java SE 21 - var Restrictions
Submit