Java var
The var Keyword
The var
keyword was introduced in Java 10 (released in 2018).
The var
keyword lets the compiler automatically detect the type of a variable based on the value you assign to it.
This helps you write cleaner code and avoid repeating types, especially for long or complex types.
For example, instead of writing int x = 5;
, you can write:
When using var
, the compiler understands
that 5
is an int
.
Example with Different Types
Here are some examples showing how var
can be used to create variables of different types, based on the values you assign:
Example
var myNum = 5; // int
var myDouble = 9.98; // double
var myChar = 'D'; // char
var myBoolean = true; // boolean
var myString = "Hello"; // String
Important Notes
1. var
only works when you assign a value at the same time (you can't declare var x;
without assigning a value):
var x = 5; // OK
var x; // Error
2. Once the type is chosen, it stays the same. See example below:
var x = 5; // x is now an int
x = 10; // OK - still an int
x =
9.99; // Error - can't assign a double to an int
Why Use var?
For simple variables, it's usually clearer to write the type directly (int
, double
, char
, etc.).
But for more complex types, such as ArrayList
or HashMap
, var
can make the code shorter and easier to read:
Example
// Without var
ArrayList<String> cars = new ArrayList<String>();
// With var
var cars = new ArrayList<String>();
Don't worry if the example above looks a bit advanced - you will learn more about these complex types later. For now, just remember that var
was introduced in Java 10, and if you work with others, you might see it in their code - so it's good to know what it means.