6 Tips and Tricks to avoid NullPointerException | Prafful Lachhwani

1. Overview

2. What is NullPointerException

3. How to avoid NullPointerException?

3.1. Using Optional Class

  • public boolean isPresent() - Returns true if there is a value present, otherwise false.
  • public T get() - If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
  • public T orElseGet(Supplier<? extends T> other) - Returns the value if present, otherwise invoke other and return the result of that invocation.

3.2. Using StringUtils

  • public static boolean isNotBlank(CharSequence cs) - Checks if a CharSequence is not empty, not null and not whitespace only.
  • public static boolean equals(CharSequence cs1, CharSequence cs2) - Compares two CharSequences, returning true if they represent equal sequences of characters. Returns true if both arguments are null.

3.3. Using Primitive Datatypes

  • int instead of Integer.
  • boolean instead of Boolean.
  • float instead of Float.
  • double instead of Double.
  • long instead of Long.
  • short instead of Short.
  • char instead of Character

3.4. Calling equals on literal

3.5. Using Ternary Operator

3.6. Throwing IllegalArgumentException

4. Conclusion



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prafful Lachhwani

Prafful Lachhwani

Full Stack Developer | ex-TCS | Winner SIH 2018