Talk:Java Programming/Preventing NullPointerException

I think the majority of these suggestions are fairly worthless.
 * Sometimes it is necessary to create an object outside of a block and it must be initilaized. The most efficient way is to use a null.
 * Making all fields final does nothing. A final field means it cannot be changed and an object often needs to be mutable.  A good programmer will always check if something is null if he is unsure
 * Using the {...} constructor for arrays is only useful if you are filling it as it is defined. Again, the new Object[...] syntax is fine if the programmer is smart enough not to check for null data before using it.

I think you mean to declare a variable outside a block, e.g., in the following code I want to find a String that starts with a b.

String[] strings={"banana","apple","pear"}; String found=null; for (int a=0;a<strings.length && found==null;a++) if (strings[a].startsWith("b")) found=strings[a]; System.out.println(found);

This would be simpler without null:

String[] strings={"banana","apple","pear"}; for (int a=0;a<strings.length;a++) if (strings[a].startsWith("b")) System.out.println(found);

If this doesn't clarify things, please provide a code example where null is preferable.

Yes, an object often needs to be mutable. But often an object doesn't need to be mutable, and where that is true, final may be useful. Note that the rules are not intended to be applied to ALL code.

Using {...} for arrays is only useful if you are filling it as it is defined. I absolutely agree. If you are not filling it as it is defined, then you should be using a Collection, which will grow as you fill it. Again, provide a code example.

I think assuming that programmers are smart is a bad idea. Even good programmers have bad days.

Most of the case you want to initialize object references to null, when you have try block, you want to create the object in the try block, and also you need the object in the catch block for logging porposes. Ervinn 23:48, 9 August 2006 (UTC)

Make all fields final
The final keyword will convert the variables to constants, but what if I need a variable. I'd like to delete that whole section 'Make all fields final', is nothing to do with preventing NullPointerExceptions. Ervinn 03:19, 21 August 2006 (UTC)

Do not use reflection (thus cheating to create an array full of null pointers)
I'd like to delete this one also, because usually we would use reflection only when that is needed. Ervinn 03:26, 21 August 2006 (UTC)
 * I agree with you. It should not appear here. Ftiercel (discuss • contribs) 18:46, 9 August 2013 (UTC)