java: cannot infer type for local variable, cannot use var on variable without initializer


Java Cannot infer type var on variable without initializer
java: cannot infer type for local variable myVar

If you get a Compile-Time Error "cannot infer type for local variable" in your Java code, then surely you are using JDK 10 or above and you are using var - local variable type inference in your program,

You will get the inferred type for local variable error when you declare a var local variable but do not initialize it. You need to make sure that you do declaration and initialize together,

Error prone code:
package examples;

/**
 * 
 * Code2care.org Java Programs
 * Date: 7-Apr-2022
 * Ver: v1.0
 * 
 */
public class VarExampleJava {

    public static void main(String[] args) {
        //some code
    }
    
    public void myMethod() {
       var myVar; //CE: Cannot infer type: 'var' on variable without initializer
        System.out.println(myVar);
    }
    
}
Error:
/Users/c2c/java_11/src/examples/VarExampleJava.java:10:13
java: cannot infer type for local variable myVar
  (cannot use 'var' on variable without initializer)
Solution:

As said before, you need to initialize the var variable,

    public void myMethod() {
       var myVar = "";
        System.out.println(myVar);
    }

Top Hashtags:

Advertisements

Advertisements




Advertisements