Defining a Live Template for Null-Check
March 11th, 2006 by Alexandra RusinaNote This tip&trick was contributed by both Bas Leijdekkers and Etienne Studer.
The Live Templates provided by IntelliJ IDEA are very convenient while programming, due to their smart and context-aware behavior. On top of the predefined Live Templates, one can add custom Live Templates. For example, you can add a Live Template that creates the code to check a variable for null, intelligently suggesting all non-primitive variables in scope as candidates.
1. Open IDE Settings | Live Templates, and click the Add button.
2. Specify the fields as shown on the screenshot below.

This particular example throws NPE if the expression is null. If you want just to create a conditional statement, you can write the following template text:
if($EXPR$==null) {$END$;}
In this case, the caret will be simply placed inside the if block.
3. Now it is necessary to specify the meaning of the “EXPR†variable. Click Edit variables and specify values as shown below.

Once the custom Live Template is defined, you can type its abbreviation (ncheck) in your Java code, and then press Tab. IntelliJ IDEA will fill in the null-check, allowing you to choose from all objects and variables in scope.
For example, if you want to check constructor parameters for null, it will look like shown below.


March 11th, 2006 at 12:18 pm
I know it isn’t the point of the example… but I find it amusing that the NullPointer check is itself a victim of a NullPointer (o.toString() will always result in an NPE in your example).
March 12th, 2006 at 11:01 am
Ooops…
Corrected. Thanks for the comment.
March 13th, 2006 at 9:31 am
Another Cool Live Template Example here:
http://tinyurl.com/q3wde
March 14th, 2006 at 1:24 am
It’s not really a NullPointerException until an attempt to dereference null has been made. Until then it’s an IllegalArgumentException.
March 14th, 2006 at 8:14 am
IDEA’s blog
TrackBack From:http://www.blogjava.net/martinx/archive/2006/03/14/35302.html
March 15th, 2006 at 11:24 am
Notice that in Demetra we’ll have an option to insert such guard code for checking null values to be passed to @NotNull parameter or null returned by @NotNull method automatically during compilation process.
June 19th, 2009 at 3:17 am
[...] create a new Live Template and set the name to something like “fpc”. The template [...]
December 13th, 2010 at 5:15 pm
[...] create you’re own templates, I would recommend you take a look at this Jetbrains blog post describing how to create a null-check [...]
September 8th, 2011 at 1:59 am
This is one I wrote:
org.apache.commons.lang.Validate.notNull($EXPR$, “Method called with null parameter ($EXPR$)”);