0

I declared var type variable however the program throws compilation error. Can someone suggest the reason for this error?

var avg2 = 10.0;

Error:

javac "VarTypeVariables.java" (in directory: S:\29032020 Java\12 Var Type Variables)
VarTypeVariables.java:12: error: cannot find symbol
        var avg2 = 10.0; //type based on 10.0 (i.e double)
        ^
  symbol:   class var
  location: class VarTypeVariables
1 error
Compilation failed.

Code:

class VarTypeVariables {
    public static void main (String args[]){
        var avg2 = 10.0; 
    }
}
6
  • Which Java version are you using? Commented Apr 13, 2020 at 6:39
  • 2
    var works in Java 10+ Commented Apr 13, 2020 at 6:39
  • @Eran I have java : Commented Apr 13, 2020 at 6:51
  • @Eran I have : C:\Users\Sandun_S_V>java -version java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) Commented Apr 13, 2020 at 6:51
  • 4
    What you show there says you're running Java 8. You need to upgrade to Java 10 or newer to be able to use var Commented Apr 13, 2020 at 6:55

5 Answers 5

2

The output from the java -version command you posted above indicates you are using Java 8. var was only introduced in to the language at java 10.

If you want to use var you need to install a more recent version of Java - Java 10 or above.

Sign up to request clarification or add additional context in comments.

Comments

0

var keyword was added in java 10 for type inference. You have to upgrade to this version of java to make this example working.

Comments

0

The reason may be you are using an older version of java. In Java 10, the var keyword has been introduced. e.g. instead of doing String str = "Java", you can now just say var str = "Java".

Comments

0

I already had the Java 17 version in use and it still didn't work. So I made the settings below and it worked.

Add to pom.xml:

<maven.compiler.release>17</maven.compiler.release>
<java.version>17</java.version>

Go to: Settings > Build, Execution, Deployment > Compiler > Java Compiler

IMG

Comments

0

I get the same error using java 17. I change java version on spring boot project in the same moment the project was running. And after this state showed up.

To fix this, change java version again e clean your project with > mvn clean, after reload the project and its done!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.