What is the var keyword in Java?

In Java, every variable has a data type. The data type specifies the type of values the variable can store.

The var keyword

Java 10 introduced a new way to declare variables using the var keyword.

The following is an example of variable declaration using var:

var name = "John Doe";

How does Java determine the type of a variable declared with the var keyword? The answer is simple. Java automatically infers the type of a variable using the initial value assigned to a variable declared with var.

In the variable declaration above, Java infers that the type of the name variable is a String.

Due to this automatic inference of the type of a variable, it is necessary to always assign an initial value to the variable.

For example, the following is not allowed:

var name;   // ERROR

Code example

The following is an executable example that shows the var keyword in action.

class main {
public static void main(String[] args) {
// Int
var x = 10;
// Double
var y = 2.10;
// Char
var z = 'a';
// String
var p = "John";
// Boolean
var q = false;
// Type inference is used in the var keyword in
// which it automatically detects the data type
// of a variable
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(p);
System.out.println(q);
}
}

One good thing about the var keyword is that it removes the duplication of the type of a variable, as shown below:

// Without var
Student stu = new Student();
// With var
var stu = new Student();

Limitations of var

Although a really useful feature, var does have some limitations. Some of them are mentioned below:

  • We cannot use it to declare local variables inside methods. We cannot use it to declare method parameters or instance fields.

  • We cannot use it to specify the return type of a method.

  • We cannot use it with a generic type.

    var<String> names = new ArrayList<String>(); // ERROR
    

Free Resources