Java MCQ: What is the primary purpose of the var keyword introduced in Java 10?
Answer:
Explanation:
The var
keyword, introduced in Java 10, is used to infer the type of a local variable at compile-time. This feature, known as Local-Variable Type Inference, allows developers to declare local variables without explicitly specifying their types. Instead, the compiler infers the type based on the initializer’s value.
For example, instead of writing:
String name = "John";
You can use var
to let the compiler infer the type:
var name = "John";
Here, the compiler automatically infers that name
is of type String
. The use of var
can make code more concise and improve readability, especially when the type is obvious from the context.
However, var
can only be used for local variables within methods, constructors, or initialization blocks; it cannot be used for fields, method parameters, or return types.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html