Java var Keyword
In this page:
What is var?
The var keyword, introduced in Java 10, lets the compiler infer a local variable's type from the value assigned to it, so you can skip writing the type explicitly while the variable still remains strongly typed underneath.
Example: What is var?
public class Main {
public static void main(String[] args) {
var age = 25; // compiler infers 'int' - still strongly typed
System.out.println(age);
}
}
Login to try C/C++/Java/PHP code in the editor
Type Inference with var
Type inference with var examines the expression on the right-hand side of the assignment at compile time and assigns that same type to the variable permanently, whether it's an int, double, boolean, or any other type.
Example: Type Inference with var
public class Main {
public static void main(String[] args) {
var price = 19.99; // inferred as double, permanently
var name = "Java"; // inferred as String, permanently
System.out.println(price + " " + name);
}
}
Login to try C/C++/Java/PHP code in the editor
var with Collections
var is especially useful with verbose generic collection types like ArrayList<String> or HashMap<String, Integer>, since it removes the need to repeat the same long type name on both sides of the declaration.
Example: var with Collections
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
var names = new ArrayList<String>(); // instead of ArrayList<String> names = new ArrayList<String>();
names.add("Alice");
System.out.println(names);
}
}
Login to try C/C++/Java/PHP code in the editor
Restrictions on var
var only works for local variables with an initializer on the same line, cannot be used for fields, method parameters, or return types, and cannot be reassigned to a value of a different type once its type has been inferred.
Example: Restrictions on var
public class Main {
// var field; // ILLEGAL - cannot use var for a class field
public static void main(String[] args) {
var count = 1;
count = 2; // OK - still an int
// count = "two"; // ILLEGAL - cannot reassign to a different type
System.out.println(count);
}
}
Login to try C/C++/Java/PHP code in the editor
When to Use var
var is most useful when the type is already obvious from the right-hand side of the assignment, such as new ArrayList<String>(), but an explicit type is often clearer when a bare literal or method call doesn't reveal what the value represents.
Example: When to Use var
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
var list = new ArrayList<String>(); // clear from the right-hand side
int total = 5; // explicit type clearer than a bare literal with var
System.out.println(list.size() + total);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: