I am trying to check if the input is null then output should be null Or if the input is String, then it should convert it to Long
Assuming input is never "abcd", input is either null or "12", "14", etc.
The following code snippet throws null pointer exception, as I am not able to use Java 8 Optional properly. I can catch the null pointer exception or use if/else with tertiary'?' operator but Is there any way to handle this scenario with Optional?
public class OptionalClass {
public void methodA(String input) {
System.out.println(Long.valueOf(Optional.ofNullable(input).orElse(null)));
}
public static void main(String[] args) {
new OptionalClass().methodA("12");// This works fine
new OptionalClass().methodA(null); // This throws null pointer exception
} }
Optionalis for. And you don't want to be catching NPE. Just use the tertiary although a better design is to say the contract simply does not allow null - then throwing the NPE is what is supposed to happen and happens automatically and your code is much simpler.ternary? :-) IMO there is no need to use Optional in your case. Something likeinput != null ? Long.valueOf(input) : nullseems ok. What @pvg says is also reasonable.