6 new Java features you shouldn’t miss


Java quietly underwent one of the biggest development changes in 2018 with the adoption of a rate of new versions. This bold new plan has allowed Java developers to get a new feature release every six months.

It’s wonderful for keeping Java fresh and relevant, but it’s pretty easy to miss out on features as they’re introduced. This article summarizes and gives an overview of several useful new features.

The optional class

One of the most common errors is the null pointer exception. And while it may be familiar, it is a very wordy problem to be wary of. At least that was until Java 8 introduced (and Java 10 refines) the Optional to classify.

In essence, the Optional The class allows you to wrap a variable and then use the wrapper methods to deal with nullity more succinctly.

List 1 contains an example of a garden variety null pointer error, in which a class reference, foo, is zero and a method, foo.getName(), is accessible on it.

Listing 1. Null pointer without optional

public class MyClass {
    public static void main(String args[]) {
      InnerClass foo = null;
      System.out.println("foo = " + foo.getName());
class InnerClass {
  String name = "";
  public String getName(){
      return this.name;

Optional offers a number of approaches to deal with such situations, depending on your needs. It sports a isPresent() method you can use to do an if-check. It ends up being quite wordy, however. Corn Optional also has methods for functional manipulation. For example, List 2 shows how you can use ifPresent() – notice the difference of a letter with isPresent() – to execute the exit code only if there is a value present.

Copyright © 2021 IDG Communications, Inc.


Source link