In this post under Java language, I will introduce you to one of the restrictions that apply to var variable.
In the previous post under Java language, I introduce you guys to var variable (local variable type inference variable) and also covered some restrictions to remember when declaring var variable.
But didn’t covered this restriction as it required a little more explanation and an example.
In this post we will cover both.
For recap, I am listing the things that we discussed in previous post
- The var variable declaration is allowed only for local variable i.e., inside a method, constructor, static, and non-static block.
- You should initialize the variable when declaring it
- var is not allowed in multi variable declaration.
- The var variable declaration is not allowed for class fields (static or non-static), constructor parameters, method parameters.
After declaring a non-var variable with datatype, we can change its value in following steps but when changing its value, we should make sure that the new value is of same datatype as the variable.
For example, in the below code, I declared an integer variable “sum” and initialized it to 0. In the following steps I changed the value to 5, as 5 is also integer.
int sum = 0;
.
.
.
sum = 5;
The above code works. But what about below code. This will fail because “5.0” is float and not integer. So compiler will throw an error.
int sum = 0;
.
.
.
sum = 5.0;
The same rule applies to var variable.
When the var variable is declared and initialized in the same line. The compiler infers the datatype of the var variable from its initialized value.
Once inferred, we can change the value of the var variable in the following steps but we have to make sure that the new value is of same datatype as the inferred one, otherwise the compiler will throw error.
Below is an example which will work, as the initialized value of var variable “sum” and new value “5” is of same datatype.
var sum = 0;
.
.
.
sum = 5;
Below is an example which will not work, as the initialized value of var variable “sum” is int and the new value “abc” is a string.
var sum = 0;
.
.
.
sum = "abc";
Below is an example for your reference
Main class
package core.language;public class LVTIExample2 { public static void main(String[] args) { var i = 30; System.out.println("i: " + i); System.out.println("After value change"); //i = "hello"; i = 60; System.out.println("i: " + i); }}
If you run the code as it is, it will run successfully.
If you remove the commented code and try to run, you will get compiler error.
So remember when you are changing the value of var variable after its declaration and initialization, make sure the new value datatype is same as inferred datatype.