Why should var keyword not be used in an instance and global variable declaration in Java 10

1k Views Asked by At
class Demo3 {
  
    // instance variable
    var x = 50;
    public static void main(String[] args)
    {
        System.out.println(x);
    }
}

Reference: https://www.geeksforgeeks.org/var-keyword-in-java/

2

There are 2 best solutions below

0
Splint On

You don't. The var keyword can only be used within a method scope while also being initialized immediately. Hence, instance variables can not be type inferred.

0
Till Brychcy On

var can only be used for local variables. fields etc. were explictly excluded, see JEP 286.

In an Update on JEP 286, Java Language Architect Brian Goetz expressed a strong opinion about using it for fields:

"[...] is fields -- but applying type inference there would be foolish."