Skip to main content

Posts

Showing posts with the label advanced java

Different ways to create Optional objects in Java 8

 In Java 8,  Optional<T>  is a container object used to represent the presence or absence of a value. It's commonly used to avoid  null  checks and  NullPointerException .  Below are different ways to create an  Optional  object in Java 8: 1.  Using  Optional.of(T value) Creates an  Optional  with a non-null value. String name = "John" ; Optional< String > optional = Optional.of( name ); 🔴 Throws  NullPointerException  if  name  is null. 2.  Using  Optional.ofNullable(T value) Creates an  Optional  that may hold a null value. String name = getName(); // could return null Optional< String > optional = Optional.ofNullable( name ); ✅ Safe way to wrap possibly null values. 3.  Using  Optional.empty() Creates an explicitly empty  Optional . Optional< String > optional = Optional.empty(); ✅ Used to represent absence of a value clearly. 4.  Using...