String str = null; OptionaloptionalStr = Optional.fromNullable(str); if (optionalStr.isPresent()) { System.out.println(optionalStr.get()); // This line will never execute } else { System.out.println("Value is absent"); // This line will execute }
String str = "Hello world"; OptionalIn this example, a non-null string is passed to the fromNullable() method, resulting in an Optional object with the value "Hello world". The isPresent() method is called to check if the Optional has a value, and since it does, the if block executes, printing "Hello world".optionalStr = Optional.fromNullable(str); if (optionalStr.isPresent()) { System.out.println(optionalStr.get()); // This line will execute and print "Hello world" } else { System.out.println("Value is absent"); }