Sobes.tech
Junior — Middle

What methods exist for safely working with values that can be null?

sobes.tech AI

Answer from AI

In Android and Java, several approaches are used for safe handling of potentially null values:

  1. Null check — the classic method, where the object is explicitly checked for null before use:
if (obj != null) {
    obj.doSomething();
}
  1. Optional (Java 8+) — a wrapper that may contain a value or be empty, helping to avoid NullPointerException:
Optional<String> optional = Optional.ofNullable(possibleNullString);
optional.ifPresent(s -> System.out.println(s));
  1. @Nullable and @NonNull annotations — assist static analysis and IDE warnings about potential null errors.

  2. Kotlin null safety — in Kotlin, types are non-nullable by default; for nullable types, ? is used, and for safe access, the ?. operator:

val length = nullableString?.length ?: 0
  1. Using safe call operators and Elvis operator for concise and safe access to nullable objects.

These methods help prevent null-related errors and make the code more reliable and readable.