Execution failed for task ‘:compileJava’. > invalid source release: 11

To resolve Execution failed for task ‘:compileJava’. > invalid source release:11 error, we need to check if gradle is referencing the correct version of java.

Solution 1. Set JDK version in gradle.properties file

gradle.properties file holds the project wide gradle settings. Any configuration done in IDE overrides the settings in this file.

To define a JDK version for the project, we can add it’s path in this file.

Open gradle.properties file in your project and add this line –

org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home/

Change the path of jdk according to the path in your system.

setting org.gradle.java.home variable for jdk path in gradle.properties file

Solution 2: Set Gradle JDK in IDE settings

We can explicitly set the JDK in IntelliJ Android IDE. All we need to do is to follow these steps –

  1. Open IDE Settings from File -> Settings. You can also use the shortcut ctrl + alt + s.
  2. Choose Build, Execution, Deployment option from left menu.
  3. Select Build Tools -> Gradle
  4. In right pane, select appropriate Gradle JDK from the list.

Check how it looks like in this screenshot –

Selecting Gradle JDK from settings in IDE

Solution 3: Wrong JAVA_HOME environment variable

If we have not set the JDK version in IDE then it will take it from JAVA_HOME environment variable.

Check if you set the correct path for JAVA_HOME. Follow these steps –

System Properties -> Advanced (Tab) -> Environment Variables

Solution 4: Unmatched JAVA_HOME and Installed Java

If you have a different version of Java than what is set in JAVA_HOME, then you will face unexpected outcomes. One of them is invalid source release error.

To understand this, first check the java version using this command –

java -version

Then check your JAVA_HOME environment variable and verify if the version matches in both.

If the version doesn’t match then it means JAVA_HOME is referring a version installed in user profile or some other location.

Solution 5: Set compileOptions in build.gradle(:app)

You can indicate gradle which version to use by setting java reference variable in build.gradle(:app) file.

Open build.gradle file in app module and set compileOptions

compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

Check it out in this screenshot –

setting jdk version in build.gradle(:app) using compileOptions property using sourceCompatibility and targetCompatibility values.

Conclusion

Gradle throws error Execution failed for task ‘:compileJava’ when something is preventing java to run the compiler. The second part of the error clears it – invalid source release:11. It means that we mentioned java version 11 but either it is not installed in system or the path variables are wrong.

In this article we saw 5 different reasons for this error and their solutions.