Junior — Middle
Can you give an example of a situation where the use of checked exceptions is justified?
sobes.tech AI
Answer from AI
In Java, the methods orElse and orElseGet are used with the Optional class to specify a default value if the object is absent.
orElse(T other)— takes a default value that is computed immediately when the method is called, regardless of whether the Optional has a value.orElseGet(Supplier<? extends T> other)— takes a supplier (function) that is called only if the value is absent, so the value computation is deferred until needed.
Features:
- If computing the default value is expensive or has side effects, it's better to use
orElseGetto avoid unnecessary costs. - If the value is simple and quick to compute,
orElsecan be used.
Example:
Optional<String> opt = Optional.empty();
// orElse always computes "default"
String result1 = opt.orElse(getDefault());
// orElseGet calls getDefault() only if opt is empty
String result2 = opt.orElseGet(() -> getDefault());
public String getDefault() {
System.out.println("Computing default value");
return "default";
}