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();


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.

See also  Essential Measures for Safeguarding Your Digital Data
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist