Domanda

I have a line in my Java code:

a.b=c;

Where a, b & c all are objects.

When the line will throw NullPoinnterException? When a is null, b is null or c is null or which combination of it is null?

È stato utile?

Soluzione

The statement a.b = c will throw a NullPointerException in the following instances:

  1. When a is null.
  2. If b is a primitive type (for example, int) and c is a type that can be autoboxed (unboxed in this case) to become that primitive type (for example, Integer) and c is null.
  3. If there is an aop point cut that triggers and something in the point cut throws a NullPointerException.

The statement a.b = c will never throw a NullPointerException in the following instances:

  1. b is null.
  2. c is null and there is no autoboxing.

Altri suggerimenti

If it's Java, it will throw only when a is null.

In Java a NullPointerException will be thrown any time the reference on the left hand side of the dot operator is null. In your example of "a.b=c" the only way for that expression to throw NullPointerException is if a is null. If c is null and later you try to interact with a.b, that will throw a NullPointerException, but that would be consistent with what I just said. When you interact with a.b with something like "a.b.number=42", if "a.b" is null, that will throw a NullPointerException. The first sentence in this comment sums it up. I hope that helps.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top