Java text blocks as preview in Jdk 13

Java 13
java jdk jdk13 tech

Java text blocks as preview in Jdk 13

If you’ve been programming in other languages, and maybe some shell, you probably miss in java some way to have a quick copy-paste template of texts, like for example if you want to produce configuration files. You’ve been probably annoyed by the need of constantly escaping special chars; or maybe you have to rely on some arcane feature of your IDE to do something easy as: “Java please print me this”.

With Java 13 we finally have something like this, but it’s still in preview mode, tough. So, if you want to use it, you have to pass some annoying switch both at compile time and when you run the code. The feature is known as JEP 355

I hope you find it nice if I share a setup that works in Maven, too. Hopefully when java 14 will be released AND people won’t argue that’s a stupid feature, you’ll no longer need special attentions… but that’ll be one year ahead from now, IF we’re lucky and everything goes well.

The java code

First thing first, I assume you have downloaded Jdk 13, for example from java.net.

public class Main
{
    public static void main(String[] args)
    {
        String template ="""
                  {"key1": "%s"},
                  {"key2": "%s"},
                  {"key3": "%s"},
                  """;
                  System.out.printf(template,"my-value","val2","val3");
    }
}

Enable the feature preview in Java 13

<?xml version="1.0"?>
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.test</groupId>
  <artifactId>literals</artifactId>
  <version>0.0.1</version>
  <description>play with java text blocks</description>
  <properties>
    <maven.compiler.target>13</maven.compiler.target>
    <maven.compiler.source>13</maven.compiler.source>
  </properties>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <release>13</release>
          <compilerArgs>
            --enable-preview
        </compilerArgs>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <argLine>--enable-preview</argLine>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-failsafe-plugin</artifactId>
        <configuration>
          <argLine>--enable-preview</argLine>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Running the code (enabling the preview features)

/opt/java/jdk-13/bin/java --enable-preview --source 13 src/main/java/Main.java

or

/opt/java/jdk-13/bin/java --enable-preview  -cp ./target/literals-0.0.1.jar Main

Polynomial derivatives in Java

Calculus in Java
java calculus

Develop in Scala with Emacs

Scala command completion in Emacs
java scala software dev

Compile and use Apache Cassandra with Jdk 11

Apache Cassandra 4 and Java 11
java jdk11 Cassandra databases