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.
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 –
-
Open IDE Settings from
File
->Settings
. You can also use the shortcutctrl + alt + s
. - Choose
Build, Execution, Deployment
option from left menu. - Select
Build Tools
->Gradle
- In right pane, select appropriate Gradle JDK from the list.
Check how it looks like in this screenshot –
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 –
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.