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);
}
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Convert GMT/UTC timezone in Excel to EST, CST, MST, PST, AST and HST - Microsoft
- How to know the version of Ubuntu - Ubuntu
- How to install Python 2.7.xx on macOS 12.3 Monterey or higher - Python
- How to install iTerm2 - Terminal alternative for Mac - MacOS
- Online CSV to SQL Insert Query Builder - Tools
- Import Other Python Files Examples - Python
- How to empty trash in Android Device - Android
- How to copy file name and path to clipboard in Notepad++ - NotepadPlusPlus