Java 13 with Gradle 6

Java still used for many digital product companies even today. Currently, Java is on version 13. Today I want to show how to use JDK13 with Gradle6. JDK13 has some improvements on GC(as usual), minor new methods for Strings and IO and there are 2 interesting new Experimental Features. So let's get started.


Gradle Project

Let's take a look at the build.gradle file.

buildscript {
repositories {
maven {
url 'https://plugins.gradle.org/m2/'
}
}
}
apply plugin: 'application'
apply plugin: 'java'
compileJava {
options.compilerArgs += ["--enable-preview"]
}
test {
jvmArgs '--enable-preview'
useJUnitPlatform()
}
sourceCompatibility = 13
targetCompatibility = 13
mainClassName = 'Main'
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/groups/public/' }
}
dependencies {
implementation 'org.slf4j:slf4j-api:1.7.25'
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.5.2'
}
application {
applicationDefaultJvmArgs = ["--enable-preview"]
}
view raw build.gradle hosted with ❤ by GitHub
Besides using the Java plugin. We need to set the source code compatibility and target to 13. We also need to pass additional parameters for compile, testing and running in order to enable experimental features. Now we can go to the new Experimental features in Java 13.

Java 13 Code

import java.util.Random;
public class Main{
public static void main(String args[]){
formating();
switchfun();
}
private static void formating(){
String jsonBlock = """
{
greeting: "Hello",
audience: "World",
punctuation: "!"
}
""";
System.out.println(jsonBlock);
}
private static void switchfun(){
boolean result = switch (new Random().nextInt() % 1){
case 0 -> {
System.out.println("Bool true");
yield true;
}
case 1 -> {
System.out.println("Bool false");
yield false;
}
default -> {
System.out.println("DEFAULT");
yield false;
}
};
System.out.println(result);
}
}
view raw Main.java hosted with ❤ by GitHub

So here we have 2 features. First, we have a multi-line string with """ and then we can pass a Json object without annoying scaping "\" like we had to do it before. The other cool feature is that we can use switch statements directly in a variable which makes the switch more similar to a pattern matcher.

Here is the complete code on my GitHub.

Cheers,
Diego Pacheco

Popular posts from this blog

Having fun with Zig Language

C Unit Testing with Check

Cool Retro Terminal