Java 11 features

Reading Time: 3 minutes

Oracle released Java 11 in September 2018, only 6 months after its predecessor, version 10, and java 11 Oracle JDK would no longer be free for commercial use.

In this blog, we’ll explore new features of Java 11:-

Open JDK

After java 10 there’s no free long-term support (LTS) from Oracle. Thankfully, Oracle continues to provide Open JDK releases, which we can download and use without charge.

New Features and Enhancements

New String Methods:

  • isBlank() – This method returns the boolean value. When the string is empty it returns the true and when the string is not blank it returns the false.

public class java11NewFeatures {

    public static void main(String[] args) {
        
        // returns false
        String myStr = "MyString";
        System.out.println(myStr.isBlank());

        // returns true
        String anotherStr = "";
        System.out.println(anotherStr.isBlank());

        // return true
        String anotherBlankStr = "   ";
        System.out.println(anotherBlankStr.isBlank());

    }
}

  • lines() – This method returns a collection of String. which are divided by line terminations(“\n”).
import java.util.stream.Collectors;

public class java11NewFeatures {

    public static void main(String[] args) {

        String myStr = "I\nam\ntest\nString";
        System.out.println(myStr.lines().collect(Collectors.toList()));

    }
}

Output:

[I, am, test, String]
  • repeat(n) – This method returns the nth String which we pass in this method.
public class java11NewFeatures {

    public static void main(String[] args) {

        String myStr = "testString";
        System.out.println(myStr.repeat(3));
    }
}

Output:

testStringtestStringtestString
  • stripLeading() – This method is used to remove the white space before any String.
public class java11NewFeatures {

    public static void main(String[] args) {

        String myStr = "   testString";
        System.out.println(myStr.stripLeading());
    }
}

Output:

testString
  • stripTrailing() – This method is used to remove the white space after the String.
public class java11NewFeatures {

    public static void main(String[] args) {

        String myStr = "anyString      ";
        System.out.println(myStr.stripTrailing());
    }
}

Output:

anyString
  • strip() – This method is used to remove the white space before and after the String.
public class java11NewFeatures {

    public static void main(String[] args) {

        String myStr = "    anyString      ";
        System.out.println(myStr.strip());
    }
}

Output:

anyString

New File Methods:

  • writeString() – This method is used to write some content in the file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class java11NewFeatures {

    public static void main(String[] args) {

        Path filePath = Paths.get("/home/Desktop/Files", "myFile.txt");
        try
        {
            //Write content to file
            Files.writeString(filePath, "Hello World !!", StandardOpenOption.WRITE);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • readString() – This method is used to read content in the file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class java11NewFeatures {

    public static void main(String[] args) {

        Path filePath = Paths.get("/home/Desktop/Files", "myFile.txt");
        try
        {
            //Write content to file
            Files.writeString(filePath, "Hello World !!", StandardOpenOption.WRITE);

            //Verify file content
            String content = Files.readString(filePath);

            System.out.println(content);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Pattern recognizing methods:

  • asMatchPredicate() – This method is same as Java 8 method asPredicate(), but this method will create a predicate if pattern matches with input string.
import java.util.function.Predicate;
import java.util.regex.Pattern;

public class java11NewFeatures {

    public static void main(String[] args) {

        Pattern pattern =  Pattern.compile("myStr");
        Predicate<String> predicate = pattern.asMatchPredicate();
        // return true
        System.out.println(predicate.test("myStr"));
        // return false
        System.out.println(predicate.test("anotherStr"));  
    }
}

Epsilon Garbage Collector:

This handles memory allocation but does not have an actual memory reclamation mechanism. Once the available Java heap is exhausted, JVM will shut down.
Its goals are:-

  • Performance testing
  • Memory pressure testing
  • last drop latency improvements

TimeUnit Conversion:

This method is used to convert the given time to a unit like DAY, MONTH, YEAR, and for time too.

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

public class java11NewFeatures {

    public static void main(String[] args) {

        long timeInMinutes = 25L;
        long timeInSec = 600L;
        long HoursInDays = 24;

        // Create a TimeUnit object
        TimeUnit minutes = TimeUnit.MILLISECONDS;
        TimeUnit second = TimeUnit.MINUTES;
        TimeUnit hours = TimeUnit.DAYS;

        System.out.println("Convert Minutes to milliseconds :" 
                + minutes.convert(timeInMinutes, TimeUnit.MINUTES));

        System.out.println("Convert Seconds to Minutes :" 
                + second.convert(timeInSec, TimeUnit.SECONDS));

        System.out.println("Convert Hours to Days :" 
                + hours.convert(Duration.ofHours(HoursInDays)));
    }
}

Output:

Convert Minutes to milliseconds :1500000
Convert Seconds to Minutes :10
Convert Hours to Days :1

New Method in Optional Class:

  • Optional.isEmpty() – This method returns true if the value of the object is null otherwise it returns false.
import java.util.Optional;

public class java11NewFeatures {

    public static void main(String[] args) {

        Optional optionalStr = Optional.empty();
        // return true
        System.out.println(optionalStr.isEmpty());

        Optional anotherStr = Optional.of("MyString");
        // return false
        System.out.println(anotherStr.isEmpty());
    }
}

Local-Variable for Lambda Parameters:

It allowed the use of var as the type of the local variable instead of the actual type. The compiler inferred the type based on the value assigned to the variable.

JDK 11 allows ‘var’ to be used in lambda expressions. This was introduced to be consistent with the local ‘var’ syntax of Java 10.

import java.util.stream.IntStream;

public class java11NewFeatures {

    public static void main(String[] args) {

        IntStream.of(11, 12, 13, 14, 15, 16)
                .filter((var evenNo) -> evenNo % 2 == 0)
                .forEach(System.out::println);
    }
}

References

For more information on Java 11 Features Click here.

Written by 

Sumit Raj is a java developer having experience of more than 3.1+ years. He is very interested to solve complex things in programming and also learn new technologies.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading