Java var Keyword
In this page:
Introduction to var
The var keyword, introduced in Java 10, enables local variable type inference, letting you omit an explicit type declaration whenever the compiler can determine the type from the variable's initializer. The variable is still statically typed underneath — var doesn't make Java dynamically typed, it just saves you from writing out a type the compiler already knows.
Example: Introduction to var
public class Main {
public static void main(String[] args) {
var message = "Inferred as String"; // compiler determines the type, still statically typed
System.out.println(message);
}
}
Login to try C/C++/Java/PHP code in the editor
Var with Primitive Types
You can use var with standard primitive types too, not just objects; Java infers the correct primitive type directly from the literal value you assign, such as inferring int from var x = 5.
Example: Var with Primitive Types
public class Main {
public static void main(String[] args) {
var x = 5; // inferred as int
var pi = 3.14; // inferred as double
System.out.println(x + " " + pi);
}
}
Login to try C/C++/Java/PHP code in the editor
Var in Loops
The var keyword is especially handy inside loops, where it simplifies verbose type declarations in index counters and enhanced for-loop variables, cutting down on visual clutter in code that's otherwise easy to read regardless.
Example: Var in Loops
public class Main {
public static void main(String[] args) {
for (var i = 0; i < 3; i++) {
System.out.println(i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Invalid Uses of var
The var keyword can only be used for local variables declared inside a method body or block. It cannot be used for class fields, method parameters, or method return types, all of which still require an explicit, declared type.
Example: Invalid Uses of var
public class Main {
// var field; // invalid -- fields need an explicit type
static int compute(int n) { // invalid to use var here as a parameter/return type too
var result = n * 2; // valid: local variable inside a method body
return result;
}
public static void main(String[] args) {
System.out.println(compute(5));
}
}
Login to try C/C++/Java/PHP code in the editor
Best Practices with var
Use var when the initialized value already makes the variable's type obvious at a glance, such as var list = new ArrayList<String>(). Avoid it when doing so would obscure the actual type and make the code harder for a reader to follow.
Example: Best Practices with var
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
var list = new ArrayList<String>(); // type is obvious at a glance -- good use
list.add("clear");
System.out.println(list);
}
}
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: