How to create Optional Class in java 8?

              If you want to create a code that helps in excessive null checks and Null pointer Exception. Java8 offers this feature as “Optional Class”.

Built in package used to implement optional class is “java.util”.

How to create Optional class in java?

  • First, a java program is created to show the NullPointerException.
  • This program includes a class “OptionalCls”. Inside the main function, a string variable “str” is created with 10 spaces.
  • Another string “sample” is assigned with a string “str”.Third element is converted into Uppercase and stored in sample.
  • Finally, print the sample value.

Here, is the program.

public class OptionalCls {

    public static void main(String[] args)

    {

        String[] str = new String[10];

        String sample = str[3].toUpperCase();

        System.out.print(sample);

    }

}

After the completion of this program, Open command Prompt.

Set the path.

Compile the program as follows.

C:\raji\blog>javac OptionalCls.java

Next, Run the program.

C:\raji\blog>java OptionalCls

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "<local1>[3]" is null

        at OptionalCls.main(OptionalCls.java:5)

There is no data in str. So, it shows NullPointerException.

To avoid this null exception, let us include the optional class.

The next program shows to include Optional Class.

  • ·       This program creates a String variable “checkNull” with the value “Optional.ofNullable”.
  • ·       If “checkNull.isPresent” is true, it executes the loop.
  • ·       Otherwise, it prints “The word is null”.

Program to implement Optional Class:

import java.util.Optional;

public class OptionalCls1 {    

    public static void main(String[] args)

    {

        String[] str = new String[10];

        Optional<String> checkNull = Optional.ofNullable(str[5]);

        if (checkNull.isPresent()) {

            String sample = str[5].toUpperCase();

            System.out.print(sample);

        }

        else

            System.out.println("The word is null");

    }

}

Compiling and Executing the above program, shows you the result.

C:\raji\blog>javac OptionalCls1.java

C:\raji\blog>java OptionalCls1

The word is null

These are the way of implementing Optional class in java 8. This can be useful in writing efficient and clean coding.

No comments:

Post a Comment