0

I need to have nested if condition but i see my code has the same logic for the else portion as well.

Syntax

if(outer_condition){
    if(inner_condition){

    }
    else{
        employee.setCompany("ABC");
        employee.setAddress("DEF");
    }
}
else{
    employee.setCompany("ABC");
    employee.setAddress("DEF");
}

Both Else portion has to execute the same logic, is there a way to avoid this and make single Else condition ?

Thanks

2
  • 5
    Make it a single if condition by joining both conditions with an && operator. Commented Jul 7, 2015 at 5:23
  • use if-else-if ladder or join conditions by using && operator. Commented Jul 7, 2015 at 5:23

4 Answers 4

5

You can combine both conditions with && operator.

   if (condition1 && condition2) {
      // If both conditions code
   } else {
        employee.setCompany("ABC");
        employee.setAddress("DEF");
   }

Note If the code of the if statement is absent as it seams from your code is better to replace it with

if (!condition1 || !condition2) {
    employee.setCompany("ABC");
    employee.setAddress("DEF");
}
Sign up to request clarification or add additional context in comments.

Comments

2
if(condition) // condition_1
    {

        if(condition) // condition_2
            {
                // your code 1
            }
        else
            {
               // your code 2
            }
    }
    else
    {
        // your code 2
    }

Change the above code to this...

 if (condition_1 && condition_2) {
     // your code 1
   } else {
      // your code 2
   }

Comments

0

Let's say if you define your first condition as condition1 and other as condition2, you could use this:

if (condition1 && condition2) {
  ifBlockCode();
} else {
   elseBlockCode();
}

public void elseBlockCode() {
    employee.setCompany("ABC");
    employee.setAddress("DEF");
}

public void ifBlockCode() {
    // Your logic can go here.
}

The && used here is the logical and operator. Similarly, there are logical or, not, etc operators. You could read about those online.

Comments

0
 if(condition1){
    if(condition2){
       //no code here
    }
    else{
       codesnippet1;
    }
}
else{
    codesnippet1; //same as snippet encountered above
}

Cases :

Case1. condition1 true and condition2 true -> //no code here

Case2. condition1 true and condition2 false -> //codesnippet1

Case3. condition1 false and condition2 true -> //codesnippet1

Case4. condition1 false and condition1 false-> //codesnippet1

So only if both conditions are true code doesn't execute codesnippet1

Hence you can simplify as

if(condition1 && condition2 )
{

}
else
{
   codesnippet1;
}

Comments

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.