Reputation: 393
Is it possible to avoid nested if
statements while I want to check if variable/object is null
and if variable/object meet some condition eg.
var obj = "test";
if (obj != null) {
if (obj.equals("test")) {
//do something;
}
}
Is it possible to do oneliner of this statement without defining own method which handle this ?
Upvotes: 2
Views: 1693
Reputation: 4168
You could make use of the null-conditional operator ?
and the null-coalescing operator ??
:
if(obj?.Equals("test") ?? false)
{
// do something
}
Where obj?.Equals("test")
returns null
if obj
is null
and ??
assigns false
to the if-statement if the value befor ??
is null
.
But sadly this will only work in C#, not in Java. Java only knows the conditional operator ?
but not the null-coalescing operator ??
(is there a Java equivalent to null coalescing operator (??) in C#?).
Upvotes: 2
Reputation: 4261
I suggest you to get familiar with short-circuit of conditional statements
If you will call your conditions with &&
as following:
if (obj != null && obj.Equals("test"))
{
//do something;
}
You will not get an exception, because if obj == null
it will return false
on the first parameter and will not check the second parameter of &&
statement.
The same logic is implemented in ||
- if first argument is true
another arguments will not be checked.
Short-circuiting is also implemented in java
, so you can implement nested if
s as the sequence of &&
operators both in c#
and java
.
Upvotes: 1
Reputation: 29026
Use Logical &&
instead for nesting if
. The &&
will evaluate the second condition only when the first one is true(the same thing that the nested if doing). So obj.equals("test")
will be evaluated only when the first condition is true ie., obj!=null
if(obj!=null && obj.equals("test"))
{
// do something;
}
Upvotes: 0
Reputation: 1488
operator && can permit you to do that.
if(obj!=null && obj.equals("test")){
//do something
}
Upvotes: 0
Reputation: 8200
You can also try (in Java)
"test".equals(obj)
this way, you don't have to do an explicit null check,
Upvotes: 4
Reputation: 2161
Yes, you can.
But check for null should be first, then if your object is null it would break:
var obj = "test";
if(obj != null && obj.equals("test")){
// do something;
}
Upvotes: 0