Sign Up to our social questions and Answers to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers to ask questions, answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How to avoid != null statements in java ?
If you use (or planning to use) JetBrains IntelliJ IDEA, a Java IDE, you can use some particular annotations developed by them. Basically, you've got @Nullable and @NotNull. You can use in method and parameters, like this: [code] @NotNull public static String helloWorld() { return "Hello World"; } [Read more
If you use (or planning to use) JetBrains IntelliJ IDEA, a Java IDE, you can use some particular annotations developed by them.
Basically, you’ve got @Nullable and @NotNull.
You can use in method and parameters, like this:
[code]
@NotNull public static String helloWorld() {
return “Hello World”;
}
[/code]
or
[code]
@Nullable public static String helloWorld() {
return “Hello World”;
}
[/code]
The second example won’t compile (in IntelliJ IDEA).
When you use the first helloWorld() function in another piece of code:
[code]
public static void main(String[] args)
{
String result = helloWorld();
if(result != null) {
System.out.println(result);
}
}
[/code]
Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won’t return null, ever.
Using parameter
[code]
void someMethod(@NotNull someParameter) { }
[/code]
if you write something like:
[code]
someMethod(null);
[/code]
This won’t compile.
Last example using @Nullable
[code]
@Nullable iWantToDestroyEverything() { return null; }
[/code]
Doing this
[code]
iWantToDestroyEverything().something();
[/code]
And you can be sure that this won’t happen. 🙂
It’s a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it’s not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.
See blog post More flexible and configurable @Nullable/@NotNull annotations.
See less