Sobes.tech
Junior — Middle

Kuidas aitab klass Optional vältida NullPointerException tüüpi vigu Java's?

sobes.tech AI

Vastus AI-lt

The Optional class in Java acts as a container that may hold a value or be empty (null). It helps explicitly handle the potential absence of a value, instead of directly using null, which often leads to NullPointerException errors.

Main advantages of using Optional:

  • Explicitly indicate that a value may be missing.
  • Prevent accidental method calls on null.
  • Provide convenient methods for handling missing values, such as orElse(), ifPresent(), map().

Example of usage:

Optional<String> optionalName = Optional.ofNullable(getName());

optionalName.ifPresent(name -> System.out.println(name.toUpperCase()));

String defaultName = optionalName.orElse("Unknown");

Thus, Optional forces the developer to explicitly handle cases where the value is absent, reducing the risk of NullPointerException.