🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this tutorial, we will demonstrate how to get the default value using the Optional orElse() method with an example.
The orElse() method returns the value if present, otherwise returns the default value.
Java Optional orElse() Method Example
In the below example, the orElse() method returns the default value because Optional contains a null value:
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = null;
Optional<String> stringOptional = Optional.ofNullable(email);
String defaultOptional = stringOptional.orElse("default@gmail.com");
System.out.println(defaultOptional);
}
}default@gmail.comimport java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
Optional<String> stringOptional = Optional.ofNullable(email);
String defaultOptional = stringOptional.orElse("default@gmail.com");
System.out.println(defaultOptional);
}
}ramesh@gmail.com
Comments
Post a Comment
Leave Comment