Tips & Tricks

Defining a Live Template for Null-Check

Note   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.
Defining Live Template
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.
Edit template variable
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.
Use Template

image description