Java Optional Class

Last updated on Dec 26 2022
Prabhas Ramanathan

Java introduced a new class Optional in jdk8. It is a public final class and used to deal with NullPointerException in Java application. You must import java.util package to use this class. It provides methods which are used to check the presence of value for particular variable.

Table of Contents

Java Optional Class Methods

Methods Description
public static <T> Optional<T> empty() It returns an empty Optional object. No value is present for this Optional.
public static <T> Optional<T> of(T value) It returns an Optional with the specified present non-null value.
public static <T> Optional<T> ofNullable(T value) It returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
public T get() If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
public boolean isPresent() It returns true if there is a value present, otherwise false.
public void ifPresent(Consumer<? super T> consumer) If a value is present, invoke the specified consumer with the value, otherwise do nothing.
public Optional<T> filter(Predicate<? super T> predicate) If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
public <U> Optional<U> map(Function<? super T,? extends U> mapper) If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper) If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.
public T orElse(T other) It returns the value if present, otherwise returns other.
public T orElseGet(Supplier<? extends T> other) It returns the value if present, otherwise invoke other and return the result of that invocation.
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable It returns the contained value, if present, otherwise throw an exception to be created by the provided supplier.
public boolean equals(Object obj) Indicates whether some other object is “equal to” this Optional or not. The other object is considered equal if:

  • It is also an Optional and;
  • Both instances have no value present or;
  • the present values are “equal to” each other via equals().
public int hashCode() It returns the hash code value of the present value, if any, or returns 0 (zero) if no value is present.
public String toString() It returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and may vary between implementations and versions.

Example: Java Program without using Optional

In the following example, we are not using Optional class. This program terminates abnormally and throws a nullPointerException.

1. public class OptionalExample { 
2. public static void main(String[] args) { 
3. String[] str = new String[10]; 
4. String lowercaseString = str[5].toLowerCase(); 
5. System.out.print(lowercaseString); 
6. } 
7. }

Output:

Exception in thread “main” java.lang.NullPointerException
at lambdaExample.OptionalExample.main(OptionalExample.java:6)
To avoid the abnormal termination, we use Optional class. In the following example, we are using Optional. So, our program can execute without crashing.

Java Optional Example: If Value is not Present

1. import java.util.Optional; 
2. public class OptionalExample { 
3. public static void main(String[] args) { 
4. String[] str = new String[10]; 
5. Optional<String> checkNull = Optional.ofNullable(str[5]); 
6. if(checkNull.isPresent()){ // check for value is present or not 
7. String lowercaseString = str[5].toLowerCase(); 
8. System.out.print(lowercaseString); 
9. }else 
10. System.out.println("string value is not present"); 
11. } 
12. }

Output:
string value is not present

 

Java Optional Example: If Value is Present

1. import java.util.Optional; 
2. public class OptionalExample { 
3. public static void main(String[] args) { 
4. String[] str = new String[10]; 
5. str[5] = "JAVA OPTIONAL CLASS EXAMPLE";// Setting value for 5th index 
6. Optional<String> checkNull = Optional.ofNullable(str[5]); 
7. if(checkNull.isPresent()){ // It Checks, value is present or not 
8. String lowercaseString = str[5].toLowerCase(); 
9. System.out.print(lowercaseString); 
10. }else 
11. System.out.println("String value is not present"); 
12. } 
13. }

Output:
java optional class example

 

Another Java Optional Example

1. import java.util.Optional; 
2. public class OptionalExample { 
3. public static void main(String[] args) { 
4. String[] str = new String[10]; 
5. str[5] = "JAVA OPTIONAL CLASS EXAMPLE"; // Setting value for 5th index 
6. Optional<String> checkNull = Optional.ofNullable(str[5]); 
7. checkNull.ifPresent(System.out::println); // printing value by using method reference 
8. System.out.println(checkNull.get()); // printing value by using get method 
9. System.out.println(str[5].toLowerCase()); 
10. } 
11. }

Output:
JAVA OPTIONAL CLASS EXAMPLE
JAVA OPTIONAL CLASS EXAMPLE

java optional class example

Java Optional Methods Example

1. import java.util.Optional; 
2. public class OptionalExample { 
3. public static void main(String[] args) { 
4. String[] str = new String[10]; 
5. str[5] = "JAVA OPTIONAL CLASS EXAMPLE"; // Setting value for 5th index 
6. // It returns an empty instance of Optional class 
7. Optional<String> empty = Optional.empty(); 
8. System.out.println(empty); 
9. // It returns a non-empty Optional 
10. Optional<String> value = Optional.of(str[5]); 
11. // If value is present, it returns an Optional otherwise returns an empty Optional 
12. System.out.println("Filtered value: "+value.filter((s)->s.equals("Abc"))); 
13. System.out.println("Filtered value: "+value.filter((s)->s.equals("JAVA OPTIONAL CLASS EXAMPLE"))); 
14. // It returns value of an Optional. if value is not present, it throws an NoSuchElementException 
15. System.out.println("Getting value: "+value.get()); 
16. // It returns hashCode of the value 
17. System.out.println("Getting hashCode: "+value.hashCode()); 
18. // It returns true if value is present, otherwise false 
19. System.out.println("Is value present: "+value.isPresent()); 
20. // It returns non-empty Optional if value is present, otherwise returns an empty Optional 
21. System.out.println("Nullable Optional: "+Optional.ofNullable(str[5])); 
22. // It returns value if available, otherwise returns specified value, 
23. System.out.println("orElse: "+value.orElse("Value is not present")); 
24. System.out.println("orElse: "+empty.orElse("Value is not present")); 
25. value.ifPresent(System.out::println); // printing value by using method reference 
26. } 
27. }

Output:
Optional.empty
Filtered value: Optional.empty
Filtered value: Optional[JAVA OPTIONAL CLASS EXAMPLE]
Getting value: JAVA OPTIONAL CLASS EXAMPLE
Getting hashCode: -619947648
Is value present: true
Nullable Optional: Optional[JAVA OPTIONAL CLASS EXAMPLE]
orElse: JAVA OPTIONAL CLASS EXAMPLE
orElse: Value is not present
JAVA OPTIONAL CLASS EXAMPLE

So, this brings us to the end of blog. This Tecklearn ‘Java Optional Class’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Java Optional Class"

Leave a Message

Your email address will not be published. Required fields are marked *