Javask
Javask

Reputation: 123

Prints null but doesn't throw exception

In Java, I understand that whenever we print object reference, internally toString() will be called. By default, toString() will print in this format "classname@hashcode". If this is true, then the following snippet should raise Null Pointer exception. Why does it not happen?

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?)

Could some one help me understand this?

Upvotes: 4

Views: 1346

Answers (4)

esin88
esin88

Reputation: 3199

This happens because println() doesn't invoke toString(). Instead, it invokes String.valueOf(x), which checks if x is null to prevent NullPointerException.

Check these documentation pages (or just look into the source code of PrintStream):

PrintStream.println(Object)

String.valueOf(Object)

Upvotes: 4

mhasan
mhasan

Reputation: 3709

It because in a 2D Array defined as [x][y] the x index holds the reference of the y which is a array of y elements.

So when you printed System.out.println(a);it gave its toString representtion. And when you inquired as System.out.println(a[0]); it was having a null reference hence it printed null

Upvotes: 1

SeanKelleyx
SeanKelleyx

Reputation: 1155

a is not null, you declare what a is in the first line int[][] a = new int[3][]; you never declare or set a[0] however so it is null. You can print this value and pass this value around without causing a null pointer exception. You get a null pointer exception when you try and call a method on a null value. So you would get a null pointer exception if you called a[0].toString() or any other method on that null value.

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

Upvotes: 0

Łukasz Kolek
Łukasz Kolek

Reputation: 41

println checks for null and instead print null, without calling toString. It is something like: println(Object x){ out.append( (x!=null)?x.toString():"null" ); out.append("\n"); }

Upvotes: 0

Related Questions