2

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 ?

2
  • 3
    "will obviously fail if obj is null." - Have you tried it?.. Commented Oct 20, 2016 at 8:05
  • 1
    Yes, it's called short-circuiting. Check this: stackoverflow.com/questions/8759868/… Commented Oct 20, 2016 at 8:06

6 Answers 6

4

You can also try (in Java)

"test".equals(obj)

this way, you don't have to do an explicit null check,

Sign up to request clarification or add additional context in comments.

Comments

2

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#?).

Comments

1

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 ifs as the sequence of && operators both in c# and java.

Comments

0

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;
}

Comments

0

operator && can permit you to do that.

if(obj!=null && obj.equals("test")){
    //do something
}

Comments

0

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;
}

3 Comments

this will throw null exception if obj ==null
No, it won't because he is using &&
@user2925656 : The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.