What is the Null Pointer Exception exception ( java.lang.NullPointerException ) and why can it occur?

What methods and means to use to determine the cause of this exception, leading to the premature termination of the application?

Translation of the question “ What is a Null Pointer Exception, and how do I fix it? » @Ziggy .

4 answers 4

When you declare a variable of a reference type, you actually create a reference to an object of this type. Consider the following code to declare a variable of type int:

 int x; x = 10; 

In this example, the variable x is of type int and Java initializes it as 0. When you assign a value of 10 to the variable (second line), this value is stored in the memory location referenced by x .

But when you declare a reference type, the process looks different. Look at the following code:

 Integer num; num = new Integer(10); 

The first line declares the variable num , its type does not refer to the built-in, therefore, the value is a reference (the type of this variable, Integer , is a reference type). Since you have not yet indicated what you are going to refer to, Java will assign the variable the value Null , meaning "I do not refer to anything."

In the second line, the new keyword is used to create an object of type Integer . This object has an address in memory that is assigned to the variable num . Now, with the help of the variable num you can access the object using the dereference operator . .

The exception that you are talking about in the question arises if you declared a variable but did not create an object, that is, if you try to dereference num before you create an object, you will receive a NullPointerException . In the simplest case, the compiler will detect the problem and report that

num may not have been initialized

What it says: "maybe the variable num not initialized."

Sometimes an exception is caused by the fact that the object was not really created. For example, you may have the following function:

 public void doSomething(Integer num){ // Работаем с num } 

In this case, the creation of the object (the num variable) lies in the calling code, that is, you assume that it was created earlier — before the call to the doSomething method. Unfortunately, the following method call is quite possible:

 doSomething(null); 

In this case, the value of the num variable will be null . The best way to avoid this exception is to check for equality to zero. As a result, the doSomething function should be rewritten as follows:

 public void doSomething(Integer num){ if (num != null) { // Работаем с num } } 

As an alternative to the previous example, you can tell the caller that the method was called with invalid parameters, for example, using IllegalArgumentException .

 public void doSomething(Integer num){ if (num == null) throw new IllegalArgumentException("Num не должен быть null"); // Работаем с num } 

Also, pay attention to the question “ What is stack trace and how can you find errors when developing applications with it? ".

Translation of the answer “ What is a Null Pointer Exception, and how do I fix it? » @Vincent Ramdhanie .

  • 2
    public void doSomething(Integer num){ if (num == null) throw new IllegalArgumentException("аргумент num не должен быть null"); ... } also insist on doing so public void doSomething(Integer num){ if (num == null) throw new IllegalArgumentException("аргумент num не должен быть null"); ... } public void doSomething(Integer num){ if (num == null) throw new IllegalArgumentException("аргумент num не должен быть null"); ... } - Sergey
  • one
    and annotations like @NonNull? In my opinion, they better reflect intent. - pavel
  • four
    Since Java labels, and 2016 is the yard, add Optional - Nofate in ways of dealing with NPE
  • one
    You can also recall Objects.requireNonNull . "may not have been initialized" is a little about something else. In java, the fields of an object without an explicit initializer are filled with default values ​​( null for reference types), but local variables are not. The message "may not have been initialized" says that there is an execution path in which a variable is never assigned a value. To get NPE in this code is impossible, because it just won't compile. - zRrr 2:29 pm
  • one
    @PavelMayorov Please complete the answer or write your own! - Nicolas Chabanovsky

The Optional class has been added to java8 to prevent a NullPointerException , although it is not always possible to use it for its intended purpose. Here is a link with recommendations on how to use Optional

Typical solution with a null check

 Article article = getFirstJavaArticle(); if (article == null) { article = fetchLatestArticle(); } 

And now the solution using Optional<T> . Imagine that getFirstJavaArticle() returns an Optional<Article>

 getFirstJavaArticle() .orElseGet(this::fetchLatestArticle); 

The solution with Optional allows us to avoid code with checks for null and work in a functional style. It is worth noting that Optional is not a panacea for all ills

The pattern NullObject is also used to prevent NullPointerException .

Abstract Entity class

 public abstract class AbstractCustomer { protected String name; public abstract String getName(); } 

Real implementation

 public class RealCustomer extends AbstractCustomer { public RealCustomer(String name) { this.name = name; } @Override public String getName() { return name; } } 

NullObject implementation

 public class NullCustomer extends AbstractCustomer { @Override public String getName() { return "Not Available in Customer Database"; } } 

Usage (as an example)

 public class CustomerFactory { public static final String[] names = {"Rob", "Joe", "Julie"}; public static AbstractCustomer getCustomer(String name){ for (int i = 0; i < names.length; i++) { if (names[i].equalsIgnoreCase(name)){ return new RealCustomer(name); } } return new NullCustomer(); } } 

Instead of returning null we return an instance of the NullCustomer class and do not fall from a NullPointerException . But I think there is a small Overhead: it is necessary to create a hierarchy of inheritance.

  • Thanks for your reply! Please, could you directly in the answer here on the site disclose the information to which you refer in the minimum necessary form ? - Nicolas Chabanovsky

This is an Exception that occurs when you refer to an object that is = null (not initialized) or you try to call methods / access variables of an object that is = null. The solution to this problem is:

  1. Check for null, if(Твой объект==null){//Your code}

  2. try{}catch(NullPointerException e){//Your code}

  3. When you throw a null, it usually indicates a "hierarchy of lines" (which is what was called, which led you to null). And there you can see where your object is not initialized, and there you can immediately correct the error.

  4. It may occur in arrays / lists when you call object number n, despite the fact that the object is not previously recorded there. Look like that's it))

  • 6
    For (2) can easily dismiss. And in general, the answer adds absolutely nothing new compared to what is already there. - D-side
  • for the second they can be fired, but in general, if, for example, work is done on a 24/7 server, a null pops up, then after the ketch block you can offer a solution (write an error to the log / console (although so few people do), then you can read the log and deal with errors, so this option also has the right to be - Space Digi
  • 2
    @SmartSystem write to the log a separate NPE never makes sense. If you catch an exception for writing to the log, then only at the top level and only Exception or Throwable. - Pavel Mayorov
  • This is one of the possible transformations. Naturally, you need to write all troubles to the log, not just specific ones; in my commentary, I meant all the errors above, not just zero, zero, I cited as an example - Space Digi

I advise you to use Optional to prevent NPE. This class was introduced in java 8.

For example

  @Entity public class Car { @Id @GeneratedValue private Long id; @Column(name = "name") @NotNull private String name; } 

Repository:

 public interface CarRepository extends JpaRepository<Car, Long> { Optional<Car> findById(Long id); } 

Service:

 @Service public class CarService { private CarRepository carRepository; @Autowired public CarService(CarRepository carRepository) { this.carRepository = carRepository; } public Car findById(Long id) { Car car = carRepository.findById(id).orElseThrow(() -> new RuntimeException("Requested entity was not found")); car.getHolder().setPassword(null); return car; } } 

Controller:

 @RestController @RequestMapping("/api") public class CarController { private CarService carService; @Autowired public CarController(CarService carService) { this.carService = carService; } @RequestMapping(value = "/cars/{id}", method = RequestMethod.GET) public ResponseEntity<Car> getCar(@PathVariable Long id) { try { Car carToFind = carService.findById(id); return ResponseEntity.status(HttpStatus.OK).body(carToFind); } catch (Exception ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } } } 

In this case, if the repository can not find the car, it will not throw NPE. Optional helps to avoid checks for null and reduce the code and improve its readability.

  • @NicolasChabanovsky added the code, you can see. - Pro100Denysko
  • Fine! Thank! - Nicolas Chabanovsky

Protected by a member αλεχολυτ 6 Jan '18 at 10:28 .

Thank you for your interest in this issue. Since he collected a large number of low-quality and spam responses, which had to be deleted, now it’s necessary to have 10 reputation points on the site (the bonus for account association is not counted ).

Maybe you want to answer one of the unanswered questions ?