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.
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:
In this case, the caret will be simply placed inside the
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.
Subscribe to Blog updates
Java Best Practices
Good code follows certain rules, and knowing them increases your chances of success. We’d like to share some Java best practices that will help you on your way. We'll cover the must-know tips and tricks, from broad advice on software development to Java- and project-specific know-how. Let's get star…
The Best of IntelliJ IDEA’s HTTP Client
In today's fast-paced tech world, easy and efficient management of web services and APIs is crucial. That's where IntelliJ IDEA's HTTP Client steps in, turning complex HTTP requests into a walk in the park. The HTTP Client is a feature-rich, text-based tool in IntelliJ IDEA Ultimate. It seamlessl…
Profile Java and Kotlin Code with the IntelliJ Profiler
At JetBrains, we believe that profiling Java and Kotlin code should be simple and accessible to all developers, regardless of their level of expertise. That’s why the IntelliJ Profiler puts ease of use and seamless integration at the forefront of its mission. In previous releases, we introduced a r…
History of Gradle Delegation Process in IntelliJ IDEA
Nowadays, a build tool is an essential part of any project, and IntelliJ IDEA integrates with the majority of them. Among the most popular build tools is Gradle. We’d like to give a brief historical overview of its integration with IntelliJ IDEA and the delegation process implemented inside the I…