devxlogo

Testing New Operations For Null

Testing New Operations For Null

Beginning Java programmers sometimes test the results of a newoperation for a null. The code for this test looks like this:

     Integer i = new Integer (400);    if (i == null)        throw new NullPointerException();

size=3>
This test is not wrong, but it is unnecessary. The two lines making up the if and the throw are wasted. They serve only to make the program fatter and slower.
C/C++ programmers often do this initially because testing the results of malloc() in C is necessary, and failing to do so creates a bug. In Java, however, new is not permitted to return null. If it does, the JVM is most likely crashing and the test isn’t going to help.

devx-admin

Share the Post: