2

How to avoid/handle more clear and safer NullPointerException in java-8 ?

But other than Optional class:

Optional emptyOptional = Optional.empty();

emptyOptional.ifPresent(System.out::println);

if (emptyOptional.isPresent())
     System.out.println(emptyOptional.get());

is there other way in java-8 ?

SurvivalMachine
  • 7,158
  • 13
  • 53
  • 74
Ross
  • 21
  • 2
  • 1
    Except for Optional, there's nothing more than the usual `== null` and `!= null` checks. Avoid nulls as much as possible. If you're really concerned about null-safety and are willing to, then use Kotlin, which has top-notch null-safety. – JB Nizet Jul 10 '16 at 06:52
  • which IDEA you are using ? – Elia Rohana Jul 10 '16 at 07:56

1 Answers1

0

The only feature for avoiding != null statement in java 8 is Optional, if you want to to use different patterns, you have few options:

  1. Null Object Pattern
  2. Annotation based, for example like JetBrains @NotNull/@Nullable. for more details check Java @NotNull

Moreover you can check this answer in SOF about avoiding-null-statements

Community
  • 1
  • 1
Elia Rohana
  • 266
  • 1
  • 13
  • There's also a newer list of null annotations: http://stackoverflow.com/questions/35892063/which-nonnull-java-annotation-to-use . In that thread you'll find an answer by MErnst (spec lead of JSR 308) highlighting the significant difference between "old" declaration annotations and TYPE_USE annotations (Java 8) -- As the question is specifically mentions Java 8 it is worth noting that TYPE_USE annotations allow for much more complete analysis. – Stephan Herrmann Jul 10 '16 at 16:56