ofNullable: null이 될 수도 있다
Optional< String > o = Optional.ofNullable(s1);
// 구현방법 .of()
OptionalInt i = OptionalInt.of(100);
OptionalDouble d = OptionalDouble.of(3.14);
Optional<String> s = Optional.of("apple");
System.out.println(i.getAsInt());
System.out.println(d.getAsDouble());
System.out.println(s.get());
System.out.println(i);
System.out.println(d);
System.out.println(s);
실행결과
100
3.14
apple
OptionalInt[100]
OptionalDouble[3.14]
Optional[apple]
package day7;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
public class OptionalDemo1_5 {
public static void main(String[] args) {
String s1 = "hi";
Optional<String> o = Optional.ofNullable(s1);
// System.out.println(o);
if ( s1 != null ) {
Util.print(s1);
}
else {
Util.print(null);
}
if ( o.isPresent() ) {
Util.print(o.get());
}
else {
Util.print("null");
}
}
}
public class OptionalDemo2_6 {
public static OptionalDouble divide( double x, double y ) {
return y==0? OptionalDouble.empty() : OptionalDouble.of(x/y) ;
}
public static void main(String[] args) {
System.out.println(divide(2, 0));
System.out.println(divide(4, 2));
}
}
// y == 0 ? OptionalDouble.empty() : OptionalDouble.of(x/y);
// trycatch를 써야했던 걸 간단하게 empty로 표현되게 할 수 있다.