Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
How to avoid NullPointerException in Java Java

How to avoid NullPointerException in Java

  • July 7, 2020July 13, 2021
  • by Coder Kai

Most of the developer’s idea is null checks makes the code less understandable and less reliable. Tony Hoare, who invented null references, calls them “a billion-dollar mistake”.

In object-oriented computer programming, a null object is an object with no referenced value. There are several places where null checking comes up,

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if they were an array.
  • Throwing null as if it were a Throwable value.

The first thing you need to consider to avoid NullPointerException, is try to avoid use null values. So try to have fields and local variables with non-null default values.

When you are writing your code you have control over the code. If null is a valid response, you have to check for it. 

public void method(Object object) {
  if (object == null) {
   // do something
  }
}

Otherwise, avoid using nulls as a response. When methods that return collections or arrays, return empty collections or arrays instead of nulls.

Since java 7 you can use Objects methods,

Objects.isNull(object)
Objects.nonNull(object)
Objects.requireNonNull(object)
Objects.equals(object1, object2)

Since java 8 you can use Optional class ,

object.ifPresent(obj -> ...)

Advantages of Java 8 Optional is null checks are not required, no more NullPointerException at run-time and you can develop clean and neat APIs.

In special cases like Strings and Collections you can use apache commons utility methods,

public static boolean isEmpty(CharSequence cs) //apache CollectionUtils
public static boolean isEmpty(Collection coll) //apache StringUtils
public static boolean isEmpty(Map map) //apache MapUtils

An alternative solution is to never return null and instead use the Null Object pattern. The null reference to convey the absence of an object, you can use an object which implements the expected interface, but whose method body is empty, it does nothing. The advantage of this approach over a working default implementation is that a null object is very predictable and has no side effects.

public interface Animal {
	void makeSound() ;
}

public class Dog implements Animal {
	public void makeSound() {
		System.out.println("woof!");
	}
}

public class NullAnimal implements Animal {
	public void makeSound() {
                // body is empty, it does nothing
	}
}
Android/iOS React-native heap limit allocation failed error
Avoid multiple clicks using debounce with react hooks
Coder Kai
A humble developer

Related articles

String.lines()
How to convert a string…
The new features in Java 14
JDK 14 – The new…
Java 13 features
Java 13 (JDK 13) -The…
Java 13 Switch Expressions
How to enable preview feature in Java 13 with maven.
Enable the Preview Feature in…
create a Vertx Eventbus js client
How to create a Vertx…
neo4j boltdriver
How to create a neo4j…
Servlet File Upload
Servlet File Upload
Java RMI Slider
JAVA RMI Observer Slider

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • binance Registrera dig on Higher order component wrappers using React.js and reusable components.
  • kopya site buyhacklink.com on How to create Lambda function with Terraform
  • Pamela587 on Chakra UI Animations

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress