EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java 8 Tutorial Optional Class in Java 8
Secondary Sidebar
Java Technology Tutorial
  • Java 7, Java 8 and Java 9
    • Java 7 Features
    • What's New in Java 8
    • Java 8 Features
    • How to Install Java 8
    • Java 8 Collections
    • Java 8 Collectors
    • Optional Class in Java 8
    • Java 8 Stream
    • Java 8 Interview Questions
    • Java 9 Features
  • Java servlet
    • What is Servlet
    • Servlet API
    • JAX-RS Jersey
    • Svelte Components
    • Java collection cheat sheet
    • Java collection hierarchy
    • Java collection api
    • Servlet Life Cycle
    • ServletContext
    • Servlet Filter
    • Session in Servlet
    • Session Bean
    • Entity Beans
    • Entity Framework Insert
    • What is JDB
    • Java Servlet Interview Questions
    • Servlet Types
    • Servlet Listener
    • Servlet Interview Questions
  • JSP
    • JSP Page
    • JSP if else
    • JSP property
    • JSP request
    • JSP format
    • What is JSP
    • JSP in Java
    • JSP Life Cycle
    • JSP?Architecture?
    • JSP Objects
    • Custom Tags in JSP
    • JSP Tag Library
    • JSP Directives
    • JSP Scripting Elements
    • JSP foreach
    • JSP Checkbox
    • JSP Include
    • JSP Taglib
    • JSP Scriptlet
    • JSP Declaration
    • Servlet JSP
    • JSP Redirect
    • JSP Forward
    • JSP Filters
    • JSP Formatter
    • JSP Expression
    • JSP File
    • Cookies in JSP
    • JSP Login Page
    • JSP Error Page
    • JSP getParameter
    • JSP Session
    • JSP Alert
    • JSP Implicit Objects
    • JSP Interview Questions
  • EJB
    • What is EJB
    • EJB Architecture
    • EJB Interview Questions
  • Java awt
    • What is AWT in Java
    • Java ActionListener
    • Java AWT Controls
    • Java MouseListener
    • Cron Scheduler in Java
    • JavaMail Api
    • Robot Framework with Java
    • Java Mail Properties
    • Java collection set
    • Java WindowListener
    • Java KeyListener
    • Java ItemListener
    • ScrollBar in Java
  • JSF
    • What is JSF
    • JSF Life Cycle
    • JSF Components
    • JSF Validation
    • JSF Interview Questions
  • JPA
    • What is JPA?
    • Java Persistence API
    • JPA Annotations
    • JAX-RS
    • What is ORM?
    • JPQL
  • JSTL
    • What is JSTL
    • JSTL Tags
    • JSTL replace
  • J2EE
    • What is JEE?
    • J2EE Framework
    • J2EE Architecture
  • Struct
    • What is Struts?
    • Struts Framework
    • Struts Architecture
  • Ant
    • Apache Ant
    • RESTful Services
    • Nutch Apache
    • Applet Life Cycle
    • Apache POI Dependency
  • JDBC
    • JDBC Batch Update
    • JDBC Insert
    • JDBC PreparedStatement
    • JDBC MySQL Driver
    • JFreeChart
    • JDBC Update
    • JDBC template
    • JDBC transaction
    • JDBC Types
    • JDBC Batch Insert
    • JDBC getConnection
    • JDBC connector
    • JDBC datasource
    • JDBC fetch size
    • JDBC resultset
    • JDBC Statement

Related Courses

Java Servlet Training Course

JavaFX Training Course

Jmeter Testing Training Course

Optional Class in Java 8

By Afshan BanuAfshan Banu

Optional Class in Java 8

Introduction to Optional Class in Java 8

In java 8(jdk8), java introduces a new class optional class, which is used to void NullPointerException in Java. The NullPointerException can crash the code and it is hard to avoid it without performing many null checks, but by using optional class in a program we can easily check whether a variable contains a null value or not and avoid the NullPointerException. With the help of an Optional class, we can provide alternate code to run or alternate values to return. As the optional class is a built-in class in java.util package.

Syntax:

public final class Optional<T> extends Object
{
// code of the optional class
}

As in the above syntax, the optional class is a final class which means that optional class cannot be extended and it is a generic class.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Member Functions of the Optional Class with Syntax

Member functions of the optional class are given below:

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,697 ratings)

1. empty(): This function gives an empty Optional instance(Without any value in it).

public static <T> Optional<T> empty()

2. of(T value): This function gives an Optional instance(with the given non-null value).

public static <T> Optional<T> of( T value )

3. ofNullable(T value): This function gives an Optional instance(with the given value, if non-null, else an empty Optional.

public static <T> Optional<T> ofNullable(T value)

4. get(): This function gives the optional value if the value is present, else NoSuchElementException throws.

public T get()

5. isPresent(): This function gives true if the value is present in an Optional instance, otherwise false.

public boolean isPresent()

6. ifPresent(Consumer<? super T> consumer): This function invokes the given consumer with the specified value if a value is present, otherwise nothing performs.

public void ifPresent(Consumer<? super T> consumer)

7. filter(Predicate<? super T> predicate): This function returns an Optional instance with a given value if a value is present and that matches the specified predicate, otherwise empty Optional returns.

public Optional<T> filter(Predicate<? super T> predicate).

8. map(Function<? super T,? extends U> mapper): This function returns an Optional with the specified value if the value is there, and after applying the specified mapping function the give is non-null. Otherwise empty Optional returns.

public <U> Optional<U> map(Function<? super T,? extends U> mapper)

9. flatMap(Function<? super T,Optional<U> mapper): This function returns an Optional with a specified value if a value is present and after applying the specified optional mapping function the result is non-null. Otherwise empty Optional returns.

public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper)

10. orElse( T other ): This function gives the value, if it is present, otherwise give others.

public T orElse(T other)

11. orElseGet(Supplier<? extends T> other): This function gives the value if it is there, else others will invoke and return its result.

public T orElseGet(Supplier<? extends T> other)

12. orElseThrow(Supplier <? extends C> excepSupplier ) throws C extends Throwable: This function gives the present value, if it is there, else throws the provided supplier created an exception.

public <C extends Throwable> T orElseThrow(Supplier<? extends C> exceptionSupplier) throws C extends Throwable

13. equals( Object ob ): This function returns true if given ob object is equal to this Optional object. Otherwise, return false. The ob object can be equal if it is Optional or both objects have no value present or both objects present equal value.

public boolean equals(Object ob )

14. hashCode(): This function gives the hash code if the value is present, else return 0.

public int hashCode()

15. toString(): This function gives a string format presentation of an Optional object, this presentation may be different based on the versions and implementations.

public String toString()

Examples of Optional Class in Java

Next, we write the java code to understand how null value is present in a variable when we do not initialize the variable with the following example where we without using Optional class to avoid null value, as below –

Example #1

Code:

package p1;
public class Demo
{
public static void main( String[] arg)
{
String[] info = new String[5];
info[0]="John";
info[2]=new Integer(26).toString();
info[3]=info[0].substring(0)+" "+info[1].substring(0);
// display full infor
System.out.println("All present values are :");
System.out.println("fname : "+info[0]);
System.out.println("lname : "+info[1]);
System.out.println("Age : "+info[2]);
System.out.println("fullname: "+info[3]);
}
}

Output:

Optional Class in Java 8-1.1

As in the above code, an Optional class is not used, so when we run the above program it throws a nullPointerException and terminates abnormally.

Next, we write the java code to understand optional class where we using Optional class to avoid abnormal termination, as below –

Example #2

Code:

package p1;
import java.util.Optional;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg)
{
Scanner sc= new Scanner(System.in);
String[] info = new String[5];
info[0]="John";
info[2]=new Integer(26).toString();
Optional<String> isNullfname = Optional.ofNullable(info[0]);
Optional<String> isNulllname = Optional.ofNullable(info[1]);
Optional<String> isNullage = Optional.ofNullable(info[2]);
for(int i=0; i<2;i++)
{
if(isNulllname.isPresent())
{
info[3]=info[0].substring(0)+" "+info[1].substring(0);
// display full infor
System.out.println("All present values are :");
System.out.println("fname : "+info[0]);
System.out.println("lname : "+info[1]);
System.out.println("Age : "+info[2]);
System.out.println("fullname: "+info[3]);
break;
}else
{
System.out.println("Last name is not present");
}
System.out.println("Enter last name");
info[1]=sc.next();
isNulllname = Optional.ofNullable(info[1]);
}
}
}

Output:

Optional Class in Java 8-1.2

An in the above code an Optional class is used to avoid a nullPointerExceptionand the abnormal termination, so the code executes without crashing. And when the value is provided or presents it just printing the values.

Next, we write the java code to use all optional class functions, as below –

Example #3

Code:

package p1;
import java.util.Optional;
public class Demo
{
public static void main( String[] arg)
{
String[] info = new String[5];
info[0]="John";
info[2]=new Integer(26).toString();
Optional<String> e = Optional.empty();
Optional<String> v=Optional.ofNullable(info[0]);
Optional<String> val = Optional.of(info[0]);
System.out.print("\nempty() = "+e);
System.out.print("\nofNullable(info[0]) = "+v);
System.out.print("\nofvalue(info[0]) = "+val);
Optional<String> v1=Optional.ofNullable(info[1]);
//Optional<String> val1 = Optional.of(info[1]); throw exception
System.out.print("\nofNullable(info[1]) = "+v1);
System.out.print("\nhashCode()= "+val.hashCode());
System.out.print("\nfilter.equals(\"Joseph\") ="+val.filter((st)->st.equals("Joseph")));
System.out.print("\nFilter.equals(\"John\") ="+val.filter((st)->st.equals("John")));
System.out.print("\nget()= "+val.get());
System.out.print("\nispresent() = "+val.isPresent());
System.out.print("\nval.orElse(\"Value is not present\") = "+val.orElse("Value is not present"));
System.out.print("\ne.orElse(\"Value is not present\") = "+e.orElse("Value is not present"));
System.out.print(val.orElseGet(() -> "\nElse Default Value"));
System.out.print(e.orElseGet(() -> "\nElse Default Value"));
System.out.println(val.map(String::toUpperCase));
System.out.println(e.map(String::toUpperCase));
}
}

Output:

Output-1.3

Recommended Articles

This is a guide to Optional Class in Java 8. Here we also discuss the function and working of optional class in java 8 along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. Java 8 Stream
  2. Java 8 Collectors
  3. Java 8 Features
  4. What’s New in Java 8?
Popular Course in this category
Free JavaScript Course
2+ Hours | Lifetime Access | Verifiable Certificates
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more