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);
    }
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.