The Object class from the java.util package is a container object that may or may not contain a non-null value. If a value is present then the isPresent() method returns true.
If you want to set a default value for the Optional object, then you can make use of the orElse() method with a default value passed as an argument to it.
Let's take a look at an example.
import java.util.Optional;
public class Example {
public static void main(String[] args) {
Optional<String> optionalWithValue = Optional.of("Mike");
Optional<String> optionalEmpty = Optional.empty(); // empty
Optional<String> optionalNull = Optional.ofNullable(null); // null
String value1 = optionalWithValue.orElse("No Name");
String value2 = optionalEmpty.orElse("Default Value");
String value3 = optionalNull.orElse("0");
System.out.println("Value 1: " + value1); // Output: Value 1: Mike
System.out.println("Value 2: " + value2); // Output: Value 2: Default Value
System.out.println("Value 3: " + value3); // Output: Value 3: 0
}
}

-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- CRUD operations in Spring Boot + JDBC
- Java Check Leap Year - Programs with Code Examples
- [fix] Java JDBC ConnectException: Connection refused
- How to add hours and minutes to Java Instant
- Java Program: Random Number Generator
- Java: The value of the local variable string is not used
- How to get list of all Java versions installed on macOS
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Java + Spring JDBC Template + Gradle Example
- Convert String to LocalDate in Java
- Remove Trailing zeros BigDecimal Java
- Java 8 Predicate Functional Interface isEqual() Method Example
- How to Hardcode Date in Java with Examples
- Java 8: Predicate negate() default Function Example
- Java: Collect Stream as ArrayList or LinkedList
- The Motivation Behind Generics in Java Programming
- How to Add/Subtract Days to the Current Date in Java
- Error: Can not find the tag library descriptor for
- Setting up JUnit 5 dependency with Maven Example
- Run Java Code Every Second
- How to create a tar.gz file using Java
- [Fix] java: integer number too large compilation error
- Java 8: Find the Max value in a List
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- Convert Java Array to ArrayList Code Example
More Posts:
- How to Install MongoDB in VSCode - HowTos
- How to increase macOS Terminal text font size (Big Sur) - MacOS
- Mac turn dark mode on or off using terminal command - MacOS
- Visual Studio Code available for Apple Mac ARM64 build for native M1 processor support - Microsoft
- Java monitoring and management console [jconsole] - Java
- Python: Print Exception Stack trace like Java - Python
- Add Current Date and Time in Notepad++ - NotepadPlusPlus
- How to know Rust is Installed on Mac? - Rust