Immediate Fix (Method 1): Update Your Build Configuration
The most common cause of the “invalid source release 21” error is a version mismatch in your build tool. To fix this instantly, ensure your Maven or Gradle configuration matches your installed JDK.
For Maven users, update your pom.xml file to ensure the compiler properties are set correctly:
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
If you are using IntelliJ IDEA, navigate to File > Project Structure. Ensure both the “Project SDK” and the “Project language level” are set to 21.
Technical Explanation: Why This Happens
This error occurs when your Java compiler (javac) is an older version than the source code level you are trying to compile. For example, if you try to build a project targeting Java 21 while using a JDK 17 environment, the compiler will not recognize “21” as a valid version.
The table below summarizes the compatibility requirements for Java 21:
| Component | Required Version |
|---|---|
| JDK (Java Development Kit) | Version 21.x or higher |
| Maven Compiler Plugin | Version 3.11.0 or higher |
| Gradle Toolchain | Version 8.4 or higher |

Alternative Methods to Fix the Error
Method 2: Verify Your System JAVA_HOME
Sometimes your IDE is correct, but your terminal uses an outdated JDK version. You must point your system environment variables to the JDK 21 installation path.
Check your current version by running this command in your terminal:
java -version
# And check the compiler
javac -version
If it returns anything lower than 21, update your JAVA_HOME variable in your System Environment Variables (Windows) or your .zshrc/.bash_profile (macOS/Linux).
Method 3: Configure Gradle Toolchains
If you are using Gradle, the “invalid source release” error often stems from the build.gradle file. Use the modern toolchain feature to force the correct version.
Add the following block to your build.gradle file:
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
This ensures that Gradle automatically downloads or uses the correct JDK 21 instance regardless of your local environment settings.