← Back to Advanced Java Course | Chapter 4: Modern Java Features | Lesson 2 of 12

Java var Keyword

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

java
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);
	}
}

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

java
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);
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		for (var i = 0; i < 3; i++) {
			System.out.println(i);
		}
	}
}

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

java
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));
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.