Why doesn't an array access expression of a null array throw a NullPointerException?

Consider the following code:

int[] r = null;
r[0] = 1 % 0;

I would expect this to throw NullPointerException: according to JLS Sec 15.7.1 :

The left operand of a binary operator is completely evaluated before any part of the right operand is evaluated.

=is a binary operator (shown in JLS Sec 15.2 - JLS Sec 15.26 describes assignment operators) and fully evaluates the left operand will result in NullPointerException. However, it throws ArithmeticException, indicating that the right operand is evaluated before the left operand is fully evaluated.

Why?

+4
source share
1 answer

:

...

(§15.10.3), , :

  • . , ; ( ) .

.

  • . , , .

.

  • . , .

, ArithmeticException.

  • , NULL, NullPointerException.

.

, -, 15.7.1 , , - .


, ,

int[] arr = null;
arr[0] += 1 % 0;

a NullPointerException.

JLS Sec 15.26.2 . , , , :

E1 op= E2 E1 = (T) ((E1) op (E2)), T E1, , E1 .

, () :

arr[0] = arr[0] + 1 % 0;

NullPointerException .

+4

Source: https://habr.com/ru/post/1672545/


All Articles