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



#Android #Java #Linux #Microsoft #Google #Python #MacOS #Notepad++ #Microsoft Teams #CSS #PHP #SharePoint #Html #Linux #C-Program #Bootstrap #jQuery #Sublime #Android-Studio #Facebook #Eclipse #WhatsApp #News #MySQL #Json #HowTos #JavaScript #FTP #S3


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 Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency