Java 12 - Quick Guide



Java 12 - Overview

Java 12 is a major feature release and it has brought many language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was releasd on Mar 2019, just six months after Java 11 release.

Java 12 is a non-LTS release.

New Features

Following are the major new features which are introduced in Java 12.

  • JVM Changes − JEP 189, JEP 346, JEP 344, and JEP 230.

  • Switch Expressions − A preview feature allowing switch to use lambda expression.

  • File.mismatch() method − File Comparison is made easy via mismatch method.

  • Compact Number Formatting − Numbers can be formatted like 2K, 3M etc easily.

  • Teeing Collector in Stream API − A merging operator on multiple collectors.

  • String new methods − four new methods introduced to format a string.

  • JEP 334 − JVM Constants API introduced.

  • JEP 305 − A preview feature allowing pattern matching for instanceOf.

Java 12 enhanced numerous APIs with new methods and options. We'll see these changes in next chapters.

Java 12 - Environment Setup

Local Environment Setup

If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment.

Java SE is available for download for free. To download click here, please download a version compatible with your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Right-click on 'My Computer' and select 'Properties'.

  • Click on the 'Environment variables' button under the 'Advanced' tab.

  • Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way

    C:\Windows\System32;c:\Program Files\java\jdk\bin.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Edit the 'C:\autoexec.bat' file and add the following line at the end −

    SET PATH=%PATH%;C:\Program Files\java\jdk\bin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc

  • export PATH=/path/to/java:$PATH'

Popular Java Editors

To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.

  • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/.

IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.

Java 12 - Switch Expressions

Java 12 introduces expressions to Switch statement and released it as a preview feature. Following are the changes introduced in case of new switch with expressions −

  • No fallthrough.
  • No break statment required to prevent fallthrough.
  • A single case can have multiple constant labels.
  • Default case is compulsary now.

Consider the following example −

ApiTester.java

public class APITester {

   public static void main(String[] args) {
      System.out.println("Old Switch");
      System.out.println(getDayTypeOldStyle("Monday"));
      System.out.println(getDayTypeOldStyle("Saturday"));
      System.out.println(getDayTypeOldStyle(""));

      System.out.println("New Switch");
      System.out.println(getDayType("Monday"));
      System.out.println(getDayType("Saturday"));
      System.out.println(getDayType(""));
   }

   public static String getDayType(String day) {

      String result = switch (day) {
         case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> "Weekday";
         case "Saturday", "Sunday" -> "Weekend";
         default -> {
            break "Invalid day.";            
         }
      };
      return result;
   }

   public static String getDayTypeOldStyle(String day) {
      String result = null;

      switch (day) {
         case "Monday":
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
         case "Friday":
            result = "Weekday";
            break;
         case "Saturday": 
         case "Sunday":
            result = "Weekend";
            break;
         default:
            result =  "Invalid day.";            
      }

      return result;
   }
}

Compile and Run the program

$javac -Xlint:preview --enable-preview -source 12 APITester.java

$java --enable-preview APITester

Output

Old Switch
Weekday
Weekend
Invalid day.
New Switch
Weekday
Weekend
Invalid day.

Java 12 - File mismatch method

Java 12 introduces an easy way to compare two files using following syntax −

public static long mismatch(Path path1, Path path2) throws IOException

Where

  • If there is no mismatch then 1L is returned else position of first mismatch is returned.

  • Mismatch is accounted in case if file sizes are not matching or byte contents are not matching.

Consider the following example −

ApiTester.java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class APITester {
   public static void main(String[] args) throws IOException {
      Path path1 = Files.createTempFile("file1", ".txt");
      Path path2 = Files.createTempFile("file2", ".txt");

      Files.writeString(path1, "tutorialspoint");
      Files.writeString(path2, "tutorialspoint");

      long mismatch = Files.mismatch(path1, path2);

      if(mismatch > 1L) {
         System.out.println("Mismatch occurred in file1 and file2 at : " + mismatch);
      }else {
         System.out.println("Files matched");
      }

      System.out.println();

      Path path3 = Files.createTempFile("file3", ".txt");
      Files.writeString(path3, "tutorialspoint Java 12");

      mismatch = Files.mismatch(path1, path3);

      if(mismatch > 1L) {
         System.out.println("Mismatch occurred in file1 and file3 at : " + mismatch);
      }else {
         System.out.println("Files matched");
      }

      path1.toFile().deleteOnExit();
      path2.toFile().deleteOnExit();
      path3.toFile().deleteOnExit();
   }
}

Output

Files matched

Mismatch occurred in file1 and file3 at : 14

Java 12 - Compact Number Formatting

Java 12 introduces compact formatting where we can format long numbers for decimal, currency or percentages to short form or long form. For example 1000 to 1K. Folloiwng syntax shows the usage −

NumberFormat formatter = NumberFormat.getCompactNumberInstance(
   Locale.US, NumberFormat.Style.SHORT);
   System.out.println(formatter.format(1000)
);

Consider the following example −

ApiTester.java

import java.text.NumberFormat;
import java.util.Locale;

public class APITester {
   public static void main(String[] args) {
      NumberFormat formatter = NumberFormat.getCompactNumberInstance(
         Locale.US, NumberFormat.Style.LONG);

      System.out.println(formatter.format(1000));
      System.out.println(formatter.format(1000000));

      formatter = NumberFormat.getCompactNumberInstance(
         Locale.US, NumberFormat.Style.SHORT);

      System.out.println(formatter.format(1000));
      System.out.println(formatter.format(1000000));
   }
}

Output

1 thousand
1 million
1K
1M

Java 12 - Teeing Collectors

Java 12 introduces a new method to Collectors to perform two different operations on collection and then merge the result. Folloiwng is the syntax of teeing method −

Collector<T, ?, R> teeing(
   Collector<? super T, ?, R1> downstream1,
   Collector<? super T, ?, R2> downstream2, 
   BiFunction<? super R1, ? super R2, R> merger
)

Here we are performing different functions on a collection and then merge the result using merger BiFunction.

Consider the following example −

ApiTester.java

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class APITester {
   public static void main(String[] args) {
      double mean
         = Stream.of(1, 2, 3, 4, 5, 6, 7)
            .collect(Collectors.teeing(
               Collectors.summingDouble(i -> i), Collectors.counting(),
               (sum, n) -> sum / n));

      System.out.println(mean);
   }
}

Output

4.0

Java 12 - String methods

Java 12 introduces following new methods to String for easy formatting.

indent(n) method

Adjust the indention of each line of string based on argument passed.

Usage

string.indent(n)
  • n > 0 - insert space at the begining of each line.

  • n < 0 - remove space at the begining of each line.

  • n < 0 and n < available spaces - remove all leading space of each line.

  • n = 0 - no change.

transform(Function<? super String,​? extends R> f) method

Transforms a string to give result as R.

Usage

String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());

Optional<String> describeConstable() method

Returns Optional Object containing description of String instance.

Usage

Optional<String> optional = message.describeConstable();

resolveConstantDesc​(MethodHandles.Lookup lookup) method

Returns descriptor instance string of given string.

Usage

String constantDesc = message.resolveConstantDesc(MethodHandles.lookup());

Consider the following example −

ApiTester.java

import java.lang.invoke.MethodHandles;
import java.util.Optional;

public class APITester {
   public static void main(String[] args) {
      String str = "Welcome \nto Tutorialspoint!";
      System.out.println(str.indent(0));
      System.out.println(str.indent(3));

      String text = "Java";
      String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
      System.out.println(transformed);

      Optional<String> optional = text.describeConstable();
      System.out.println(optional);

      String cDescription = text.resolveConstantDesc(MethodHandles.lookup());
      System.out.println(cDescription);
   }
}

Output

Welcome 
to Tutorialspoint!

   Welcome 
   to Tutorialspoint!

avaJ
Optional[Java]
Java

Java 12 - Garbage Collection Enhancements

Java 12 introduces multiple enhancements to its garbage collection algorithms.

JEP 189 – Shenandoah: A Low-Pause-Time Garbage Collector (Experimental)

An experimental Low-Pause-Time Garbage Collector, Shenandoah is introduced to reduce the GC pause time. It works in parallel with running java threads. This helps to reduce the dependency of GC over heap size and makes it consistent. Now Garbage collection pause time would be similar for 2 MB as well as for 2 GB heap sapce.

Shenandoah is expected to be part of main JAVA release with Java 15.

JEP 346 – Promptly Return Unused Committed Memory

With Java 12, G1 will process java heap space if application is inactive and may release the memory to operating system. This preemtive behavior conserve and free memory.

JEP 344 : Abortable Mixed Collections

With Java 12, G1 efficiency has been improved. Now G1 mixed collections are abortable if they exceed the define pause limit. Now mixed collections are spilt into mandatory and optional. G1 collector can prioritize the mandatory sets to be check the pause time goal.

Java 12 - Microbenchmark

Java 12 introduces multiple enhancements to its garbage collection algorithms.

JEP 189 – Shenandoah: A Low-Pause-Time Garbage Collector (Experimental)

An experimental Low-Pause-Time Garbage Collector, Shenandoah is introduced to reduce the GC pause time. It works in parallel with running java threads. This helps to reduce the dependency of GC over heap size and makes it consistent. Now Garbage collection pause time would be similar for 2 MB as well as for 2 GB heap sapce.

Shenandoah is expected to be part of main JAVA release with Java 15.

JEP 346 – Promptly Return Unused Committed Memory

With Java 12, G1 will process java heap space if application is inactive and may release the memory to operating system. This preemtive behavior conserve and free memory.

JEP 344 : Abortable Mixed Collections

With Java 12, G1 efficiency has been improved. Now G1 mixed collections are abortable if they exceed the define pause limit. Now mixed collections are spilt into mandatory and optional. G1 collector can prioritize the mandatory sets to be check the pause time goal.

Advertisements