Summary: in this tutorial, you’ll learn how to use the Java var
keyword to declare variables and understand how Java infers the type of variables.
Introduction to the Java var keyword
Because Java is a statically typed language, every variable in Java is associated with a data type. The data type determines the kind of values that the variable can store.
It means that when you declare a variable, you need to specify its data type upfront. For example, the following defines a variable count and initializes its value to 0:
int count = 0;
Code language: Java (java)
Java 10 introduced a new way to declare a variable using the var keyword. For example, the following declares the count
variable with type int and initializes its value to 0:
var count = 0;
Code language: Java (java)
But how does Java determine the type of the count
variable? In this case, Java automatically infers the type of the variable count
using its initial value. Because the value of the count
is zero, the count
variable has the type of int
.
Since Java uses the initial value to determine the type of variable, you need to initialize the variables declared with the var
keyword. The following example is not allowed:
var count;
Code language: Java (java)
In the following example, Java infers the type of the amount
variable as double because of its initial value 0.00
:
var amount = 0.00;
Code language: Java (java)
It’s equivalent to the following:
double amount = 0.00;
Code language: Java (java)
The var keyword also allows you to declare multiple variables at once, each variable declaration is separated by a comma (,
):
For the primitive data types, the var
keyword may not have benefits. But later, when you learn about classes, you’ll see how the var
keyword makes your code more concise. For example, instead of writing the following code:
StringBuilder builder = new StringBuilder();
Code language: Java (java)
you can shorten it down using the var
keyword:
var builder = new StringBuilder();
Code language: Java (java)
Java var and compound declaration
When you use an explicit type, you can define multiple variables using a single statement. For example:
double amount = 98.95,
salesTax = 0.08;
Code language: Java (java)
In this example, we declare two variables amount and salesTax
with the type double. This variable declaration is also known as a compound declaration.
Unlike explicit variable declarations, Java doesn’t allow you to declare multiple variables using the var
keyword in a single statement.
For example, the following will result in an error: “‘var’ is not allowed in a compound declaration”:
var amount = 98.95,
salesTax = 0.08;
Code language: Java (java)
Summary
- The Java
var
keyword automatically infers the type of a variable using its initial value. - The Java
var
keyword cannot be used in a compound declaration.