Is this bad practice or any performance hit, this is to check x is not equal to null
if( !(x == null) ){
System.out.println("x is not a null value");
}
Is this bad practice or any performance hit, this is to check x is not equal to null
if( !(x == null) ){
System.out.println("x is not a null value");
}
The normal way to do this is:
if(x != null){
System.out.println("x is not a null value");
}
There's nothing wrong with checking if the value is not null!
It is bad practice to do without making the reason to do so clear. It's not clear in your example why you are making the check. A common example might be something like
if (s == null || s.isEmpty()) // if s empty or not set.
or
if (s != null && s.length() > 0)
Usually, you do this when you need it in which case performance isn't important.
Normally you would write
if(x != null)
or better
if (x == null) {
// handle null, assuming this is not empty.
} else {
// handle not null
}
Performance-wise it is unlikely to be relevant, because you can trust the compiler to optimize that.
It's just a question of style. Style is always subjective, but I would say if (x != null)
is more concise and more readable.
if(x != null) is recommended and easy to read "X is not equal to null"
if(!(x == null)) can't be read as "X is not equal to null"
Just to add here best practice is to do
if(null != x) {
System.out.println("x is not null");
}
instead of
if(x != null) {
System.out.println("x is not null");
}
I know in java anyways will work but this will save you in other languages like c++ where you might accidently assign null to x for example,
if(x = null) {
printf("x is not null");
}
if( !(x == null) ){
System.out.println("x is not a null value");
}
well if condition returns a boolean true of false. so, writing above will not effect anything. according, to above code the condition you wrote is "if is not true" then do something! and as others have suggested to write code as if(x != null)
is better way and less confusing ;)