Open JDK version, sourceCompatibility and targetCompatibility in Android

Open JDK version, sourceCompatibility and targetCompatibility

SHISHIR
2 min readDec 23, 2023

When we install Android Studio in Mac, it comes with an embedded JDK. We can check the embedded JDK version by following command.

java --verson

The output will look something like this.

openjdk 20.0.1 2023-04-18
OpenJDK Runtime Environment (build 20.0.1+9-29)
OpenJDK 64-Bit Server VM (build 20.0.1+9-29, mixed mode, sharing)

Now by default when we will run any Gradle task, Gradle itself as well as all tasks will use this exact JDK. In this example, it would use the JDK in version 20. In other words, our source code can use features up to Java 20, and consumers of your project also require at least Java 20 to run it.

But we can change these defaults by overriding them with sourceCompatibility and/or targetCompatibility without installing another JDK.

** sourceCompatibility defines the maximum Java version of our source code will support. This means if we define sourceCompatibility to Java 11, our source files can use features up to Java 11.

** targetCompatibility defines what version of Java the output (the bytecode) will have. Therefore, this value defines the minimum required Java version that the consumer of your project ( The device will run our project) will need to run it.

If we set sourceCompaitiblity but skip to set targetCompatibility this will automatically set the same value of sourceCompatibility. But we can set the both. Generally we find below code in our app level build.gradle file.

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

This means, our source file can use features up to java version 8. And after compilation, the output bytecode will have java version 8.

Note: We must have JDK version greater than or equal to this sourceCompatibility to build the project. If you use an older JDK version than sourceCompatibility and we use any feature of sourceCompatibility version in your sources and then try to compile it, it will fail.

If we use three different Java versions what will happen?

For example, use JDK 20, set sourceCompatibility to Java 8 (for whatever reason), and set targetCompatibility to Java 11.

In this case, It will build with a Java version (20), but it will ensure that we don’t use any features that are higher than Java 8 in your source files, and the minimum Java version required to run your project is Java 11.

This is kind of theory knowledge. But we should know why we are using this and what is happening internally.

Happy Coding !

--

--

SHISHIR

{ 'designation' : 'Lead Software Engineer' , 'hobby' : [ 'Music', 'Photography', 'Travelling' ] ,’email’: ‘shishirthedev@gmail.com’ }