Prints null but does not throw an exception

In Java, I understand that whenever we print a reference to an object, toString () will be called internally. By default, toString () will print in this format "classname @hashcode". If so, then the following snippet should throw a Null Pointer exception. Why is this not happening?

int[][] a = new int[3][];
System.out.println(a);  --> Prints [a@xxxxx
System.out.println(a[0]); --> Prints null (It should have thrown Null pointer Exception?)

Can someone help me figure this out?

+4
source share
4 answers

This is because it println()does not toString(). Instead, it calls String.valueOf(x), which checks if it xis null, to prevent it NullPointerException.

Check out these documentation pages (or just look at the source code PrintStream):

PrintStream.println()

String.valueOf(Object)

+4

, , [x] [y], x y, y .

, System.out.println(a);, toString. System.out.println(a [0]); ,

+1

println null null, toString. - : println (Object x) {out.append((x!= Null)? X.toString(): "null" ); out.append( "\ " ); }

0

a , , a int[][] a = new int[3][];, a[0], null. , . . , , a[0].toString() .

https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html

0

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


All Articles