Null Checking in Java

Learnt something new today!

 

In order to prevent the accidental setting of a variable to null like so:

1
2
3
4
5
6
7
8
	private void testMethod(Boolean b) {
		if (b = null) {  //Ack! This works but is not what you want.
			//do something
		}
		if (b == null) {  //This works, and is correct
			//do something
		}
	}

 

… put the null first

1
2
3
4
5
6
7
8
	private void testMethod(Boolean b) {
		if (null = b) {  //Throws compiler error
			//do something
		}
		if (null == b) {  //This works
			//do something
		}
	}

 

javac picks up on all other datatypes except java.lang.Boolean and will throw a compiler error, so this tip is of very limited utility. Still, it’s interesting!

This entry was posted in David's Blog, News and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *