In the previous chapter, we learnt about Java Datatypes. In this chapter, let us dive deeper into the "var" keyword in Java programming language.
The “var” keyword in Java was introduced in Java version 10 in March 2018.
This keyword allows you to write code that can automatically infer the data type of a variable without any explicit type declaration.
It automatically infers the data type of the variable using the value which is assigned to the variable.
The general syntax of this keyword is given below:
var variableName = value;
Let us look at some of the examples using different data types:
var x = 40;
System.out.println(x);
var x = 5.50;
System.out.println(x);
var x = 4.544f;
System.out.println(x);
var x = false;
System.out.println(x);
var x = 'C';
System.out.println(x);
var x = "Cat";
System.out.println(x);
You can also use it to declare any non-primitive values such as ArrayList, Map, custom Objects, etc.
Here are some important points to note while using the “var” keyword in your Java programs…
You can reassign your variable after the initial declaration.
For. e.g.
var x = 40;
x = 50;
System.out.println(x); //50
While declaring the variable, it is mandatory to initialize the variable with some initial value. Without an initial value, you will get compilation error as “Cannot use 'var' on variable without initializer”
For e.g.
var x; //This is incorrect. You will get compilation error in this line.
x = 50;
As mentioned earlier, you are allowed to reassign the variable, however the reassigned value should be of the same data type as the initial value. You cannot reassign the variable with a value of different data type.
For e.g.
var x = 40;
x = “String value”; //This is incorrect. You will get compilation error.
I hope this tutorial gave you a fair understanding of Java var keyword. See you soon in the next tutorial.
Fully customizable CRM Software for Freelancers and Small Businesses