Java 12 & 13 Features


Java 12 features more helpful for the developers.
Major features are consolidated here, Please refer below.


Enhancement in switch statement. Now switch statement is a switch expression (preview). Refer below code snippet.

import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

public class TestMain {
   
public enum Weekdays{
       
MONDAY,
       
TUESDAY,
       
WEDNESDAY,
       
THURSDAY,
       
FRIDAY,
       
SATURDAY,
       
SUNDAY;
    }
   
public static void main(String args[]) {
       
new TestMain().dayOfWeek(Weekdays.MONDAY);
    }

   
public Integer dayOfWeek(Weekdays day){
       
int numLetters = switch (day) {
           
case MONDAY-> 1;
           
case TUESDAY -> 2;
           
case WEDNESDAY -> 3;
           
case THURSDAY -> 4;
           
case FRIDAY -> 5;
           
case SATURDAY -> 6;
           
case SUNDAY -> 7;
           
default -> throw new IllegalStateException("Invalid day" + day);
        };
       
return numLetters;
    }
}


New method in Collectors utility class teeing(), it takes 3 argument, 2 collectors and one bifunction, refer below code snippet.

import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestMain {

  
public static void main(String args[]) {
     
double average = Stream.of(1, 4, 2, 7, 4, 6, 5)
         .collect(Collectors.teeing(
            Collectors.summingDouble(val -> val),
//calculate the sum of input stream
           
Collectors.counting(), //calculate the count of input stream
           
(sum, n) -> sum / n));  //divide the sum by input count
       
System.out.println(average);
    }
}


A low-pause-time garbage collector
Note - This is an experimental feature and is not included in the default (Oracle’s) OpenJDK build.
Shenandoah is a garbage collection (GC) algorithm that guarantee low response times. It reduces the GC pause times by doing evacuation work simultaneously with the running Java threads. With Shenandoah, pause times are not dependent on the heap’s size. This means that pause times will be consistent no matter the size of your heap. A 10 MB or 10 GB heap should have the same pause time.
Shenandoah is a research project announced by Red Hat in 2014 that targets low-latency application requirements for memory management on the JVM


New method in String class, indent() and transform() method

Refer below code snippet-

import java.util.function.BiFunction;


public class TestMain {
    public static void main(String args[]) {
        var stringVar = "MK Study Journal";
        System.out.println(stringVar.indent(5));  //add leading space "     MK Study Journal"
       
BiFunction<String, String,String> stringConcat = (x, y) -> {
            return x + y;
        };
        BiFunction<Character, Character, Boolean> firstLatsCharCompareFunc = (x, y) -> {
            return  x.equals(y);
        };
        // transform method is used to transform the
        //String transformed result may or may not be string
       
var newConcatStringVar = stringVar.transform(s -> stringConcat.apply(s,s));
        var firstLatsCharCompare = stringVar.transform(s -> firstLatsCharCompareFunc.apply(s.charAt(0),s.charAt(s.length()-1)));
        System.out.println(newConcatStringVar);
        System.out.println(firstLatsCharCompare);
    }
}


New Method in java.io, InputStream skipNBytes(int n), will skip first N bytes.

Refer below code snippet-
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class TestMain {

    public static void main(String args[]) {
        var fileName = "MKStudyJournal.txt";
        try (InputStream inputStream = new FileInputStream(fileName)) {
            inputStream.skipNBytes(100); // this will skip first 100 bytes
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


New packge java.lang.constant which is part of JVM constant API

Every Java class file has a constant pool, which stores the operands for bytecode instructions in the class
The JVM Constants API provides symbolic reference types to describe each form of constant (class, loadable constant, MethodHandle, MethodHandle constant and MethodType constant). There is also an enumeration for the kinds of MethodHandle

This has also affected several other classes. All the following classes now have a describeConstable() method:
·        Class
·        Double
·        Enum
·        Float
·        Integer
·        Long
·        String
·        MethodHandle
·        MethodType
·        VarHandle


Comparison of two files Files.misMatch(path, path)-

Two files can have a mismatch in the below scenarios:
If the bytes are not identical. The position of the first mismatching byte is returned.
File sizes are not identical. In this case, the size of the smaller file is returned.

package com.mk.main;

import java.io.File;
import java.lang.constant.ClassDesc;
import java.nio.file.Files;
import java.nio.file.Path;

import static java.nio.file.Files.createTempFile;

public class TestMain {
    public static void main(String args[]) throws Exception{
        Path firstFilePath = createTempFile("file1", ".txt");
        Path secondFilePath = createTempFile("file2", ".txt");
        Files.writeString(firstFilePath,"MK Study Journal");
        Files.writeString(secondFilePath,"MK Study Journal test");

        long mismatch = Files.mismatch(firstFilePath, secondFilePath);
        System.out.println("File Mismatch "+ mismatch); //it will return -1 if no mismatch
   
}
}


Compact Number Formatting-

Compact number representations are much easier to read and require less space on the screen without losing the original meaning.
E.g. 3.6 M is very much easier to read than 3,600,000.
import java.text.NumberFormat;
import java.util.Locale;

public class TestMain {
   
public static void main(String args[]) throws Exception{
        NumberFormat numberFormat = NumberFormat.getCompactNumberInstance(Locale.
US,
                NumberFormat.Style.
SHORT);
        String formattedString = numberFormat.format(
25000L);
        System.
out.println(formattedString);  //25K
   
}
}


Make G1 mixed collections abortable if they might exceed the pause target.

If G1 discovers that the collection set selection heuristics repeatedly select the wrong number of regions, switch to a more incremental way of doing mixed collections: split the collection set into two parts, a mandatory and an optional part. The mandatory part comprises parts of the collection set that G1 cannot process incrementally (e.g., the young regions) but can also contain old regions for improved efficiency. This may, e.g., be 80% of the predicted collection set. The remaining 20% of the predicted collection set, which would consist of only old regions, then forms the optional part.

After G1 finishes collecting the mandatory part, G1 starts collecting the optional part at a much more granular level, if there is time left. The granularity of collection of this optional part depends on the amount of time left, at most down to one region at a time. After completing collection of any part of the optional collection set, G1 can decide to stop the collection depending on the remaining time.

As the predictions get more accurate again, the optional part of a collection are made smaller and smaller, until the mandatory part once again comprises all of the collection set (i.e., G1 completely relies on its heuristics). If the predictions becomes inaccurate again, then the next collections will consist of both a mandatory and optional part again.


Java 13 features helpful for the developers.
Major features are consolidated here, Please refer below.


Enhancement in switch statement. Now switch statement is a switch expression

Switch expression was introduced in Java 12 (Preview), now that is extended in Java 13
In Java 13 for switch expression “break” has been replaced with “yield” to return a value from the case statement.
Enable preview mode in java 13 to see this feature.
C:\Program Files\Java\jdk-13.0.1\bin>jshell --enable-preview





Text block using triple quotes

Using triple quote “””….””” Text block with multiple line can be written easily. These are very helpful in html or rich ui text.
Refer below code snippet.




5 comments: