else if and multiple if difference

Hi,

what is difference between
public class Test {
   public static void main(String args[]){
      int x = 30;

      if( x == 10 ){
         System.out.print("Value of X is 10");
      }else if( x == 20 ){
         System.out.print("Value of X is 20");
      }else if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("This is else statement");
      }
   }
}

Open in new window

and writing multiple if's as below.
public class Test {
   public static void main(String args[]){
      int x = 30;

      if( x == 10 ){
         System.out.print("Value of X is 10");
      } if( x == 20 ){
         System.out.print("Value of X is 20");
      } if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("This is else statement");
      }
   }
}

Open in new window

when to use which approach?
 Also can i have separate 'return' from all the blocks of if's and elseif's and else's?

please advise
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kanti PrasadCommented:
if then else = if true execute { execute code } else if true { execute code}  or go to else { execute code }
it is more cleaner approach
      if( x == 10 ){
         System.out.print("Value of X is 10");
        }else  {
         System.out.print("This is else statement");
      }

if-then  == if  true then  { execute code } if not no additional code is executed.
In the above case if at a later time you add any new code statements and if your braces are not closed properly you will get different results.

you can chose any of the styles but the if then else is better

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kanti PrasadCommented:
Hi

Please refer java documentation

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.

the x=30 example is what  I meant in
"if at a later time you add any new code statements and if your braces are not closed properly you will get different results"
TommySzalapskiCommented:
To answer the question more directly, if X is 20 in the first example it will just print "Value of X is 20."

In the second example, it will print "Value of X is 20This is else statement" since the else is only attached to the last if.
The way you wrote the second example is very weird from a style perspective. You made them look connected when they are not.

Use else if when you want it to only check the second condition if the first condition has failed.
Use multiple ifs when the conditions are independent.

Yes, you can put a return in each if block. Some people like that style, others prefer a single return at the end. Up to you. Of course, as soon as it hits any return, the function will stop executing so make sure that's what you really want (in the multiple if case).
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Kanti PrasadCommented:
Hi

The execution is only the difference. We can get the same outputs with either statement

if then
or
if else if else....

if there was no else in the 2nd test class then when x=40 there will not output given as no condition is true
but when x=40 in the if else if else if else in the 1st test class you will get an output and the else will protect you!!

Hence, your 2nd test class passed by luck as you luckily had and else after equating 30 .
If that else was not there then no one will know what went wrong as it will run as normal but without an output and that is what I meant that it is not a clean approach.


To understand it better the execution will take place as below

 if( x == 10 ){System.out.print("Value of X is 10");}   ( nothing else is done. it goes to the next line of code)

if( x == 20 ){ System.out.print("Value of X is 20"); }   ( nothing else is done, it goes to the next line of code)

 if( x == 30 ){ System.out.print("Value of X is 30");}  
else
{ System.out.print("This is else statement");}
(here if and else are executed sequentially so if x is not 30 it will go into else that is why when it is not 30 it will always go to the else condition.




for your 1st test class
 IF ... else if ....  else if ... else the code is executed in sequence instead of individual statements.
phoffric\Commented:
On an exam, if difference is taken to mean functional difference, then there is no difference between the two. In both cases the only output is Value of X is 30 because x was initialized to 30.

Even in performance (i.e., speed of execution), as written, both should perform identically.

From a style perspective, since the test conditions are mutually exclusive, then I agree with  gurpsbassi that the else if style should be used because this conveys to the reader just that - the test conditions should be expected to be mutually exclusive.

If, instead, you had some input or computation that resulted in x being any number, then the other experts have covered those cases.
ozoCommented:
if x has the value 10 then the programs would differ in more than just resource waste.
if x had the value 10, then one program would print "This is else statement" and the other would not.
Kanti PrasadCommented:
Hi

I am telling you can achieve the outputs by both ways in THEORY but which is a better approach is when you have multiple conditions then the better approach will be if else if else if else.

With if statements, you need to know all your conditions and one has to code for all of them and if you miss any condition then you will never know what is the value of x  if you never had an else as the else will cater for any of the conditions that is not true. say if you code for 10 , 20 & 30 and you have a value of 40 in x then without an else the program will be executed, but it will not give any outputs, which will give a normal user a feeling  that nothing happened.

 Also as if conditions are all single statements all your conditions will be executed irrespective of the condition that already is true. eg if x = 10 but still it will run through all the other conditions which normally is not required but with if else if else if else once any condition is true it will come out of the loop and this will save execution time in other terms the output will be given faster or improved performance.

If you have a return in between anywhere then it will come of out the loop as soon as it passes return.

Return is like a one way symbol once it passed it, the execution will never goes any further deep, to check any other conditions where otherwise it normally would.

Cheers

Kanti Prasad
ozoCommented:
For this particular example, assuming that to first program was what was intended, you might use
public static void main(String args[]){
        int x = 30;

        switch( x ){
        case 10: {
            System.out.print("Value of X is 10"); break;
        }
        case 20: {
            System.out.print("Value of X is 20"); break;
        }
        case 30: {
            System.out.print("Value of X is 30"); break;
        }
        default: {
            System.out.print("This is else statement");
        }
        }
}

Open in new window

or
        switch( x ){
        case 10: case 20: case 30: { System.out.print("Value of X is " + x ); } break;
        default: { System.out.print("This is else statement");}
        }

Open in new window

Kanti PrasadCommented:
Hi gurpsbassi

Show me why the below is also not dangerous  with "side effects"  AFTER IT passed if else if else if else  block

 if( x == 10 ){
         //do something....;
        x = 20;
      }else if( x == 15 ){
         //do something....;
      }else if( x == 20 ){
         //do something....;
      }else{
         //do something....;
      }

Will x not hold 20 even though it was 10 initially?

The only difference with the above is, it will not go into the loop == 20  as once x enters the if else if BLOCK with 10 the newly assigned value will not be assigned until it comes out that loop.

So the only difference is  if then statements are run as INDIVIDUAL statements  and if else if else if else are executed in BLOCK statements.

Hence if the developer does not code all true conditions well there will issues undetected in if then as there is not else to capture the unknown value say 40 / 50 but  with If else if else else you will have more control if the developer misses any true conditions.
ozoCommented:
difference is if then statements are run as INDIVIDUAL statements  and if else if else if else are executed in BLOCK statements
No, it's the { } that makes a BLOCK rather than INDIVIDUAL statements, not the if else if else if else
gudii9Author Commented:
public class TestIfAndIfAbdIf {
   public static void main(String args[]){
      int x = 30;

      if( x == 10 ){
         System.out.print("Value of X is 10");
      } if( x == 20 ){
         System.out.print("Value of X is 20");
      } if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("This is else statement");
      }
   }
}



public class TestIfAndElseIfAndElseIfAndElseIf{

	   public static void main(String args[]){
	      int x = 30;

	      if( x == 10 ){
	         System.out.print("Value of X is 10");
	      }else if( x == 20 ){
	         System.out.print("Value of X is 20");
	      }else if( x == 30 ){
	         System.out.print("Value of X is 30");
	      }else{
	         System.out.print("This is else statement");
	      }
	   }
	}

Open in new window


when i ran both above both programs i got same output
Value of X is 30
Kanti PrasadCommented:
Hi gudii9

I meant  loop as ending statement  { }  not literally loop...
and if( x == 20 ){ System.out.print("Value of X is 20");} as one  individual statement
and  if( x == 10 ){}else if( x == 20 ){}else if( x == 30 ){}else{} one block

Please refer to my "The execution is only the difference." comment where I mentioned how your code is being executed.

if( x == 10 ){  System.out.print("Value of X is 10"); this is one statement which it executes and goes to the second one.
f( x == 20 ){      System.out.print("Value of X is 20");  after this line it goes below

the below is executed as a block and if it is not 30 only it will go to else so to test it out put x = 40 on top and it will go to the else statment.
if( x == 30 ){  System.out.print("Value of X is 30"); }
else
{ System.out.print("This is else statement"); }
Kanti PrasadCommented:
Hi gudii9

As you have x = 30 on top of your program after the main only the x == 30 code will be executed in both your programs hence you are getting the same output as you have the same print 30 statement there.

Please refer my comment  starting with below as it shows the way your code is executed
The execution is only the difference. We can get the same outputs with either statement

I f you only had

if( x == 30 ){ System.out.print("Value of X is 30");} in your 2nd Test program with out an else and if you put x = 40 in both then you will get This is else statement in your 1st program and no output in your 2nd test program.
phoffric\Commented:
Looking at the responses, your question has been answered.
>> when i ran both above both programs i got same output,  Value of X is 30
I mentioned above that the two programs are functionally equivalent since x is initialized to 30.
TommySzalapskiCommented:
Yes, but run it with x = 20 and you will get different output. The else is attached only to the x == 30 case.
Putting the if on the same line as the } doesn't mean they are actually connected in any way.
gudii9Author Commented:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.

Above link giving below error.

We're sorry, the page you requested was not found.


We have recorded this error (404) to help us fix the problem.
You may wish to try again using one of the tools below.

      Back to Previous Page
      Site Map
      Product Index
      Software Download Index
      To search for your page, try our Search function.
                                                  Refine Search

i need to re-read all the posts again. I quickly went through them and had that question.
gudii9Author Commented:
. . .  and the point has been made, by gurpsbassi, that 'else if' is to be preferred over if . . if . . . if.

i got this flow

if ..if...if is natural flow of programming right where as

else if is filtering more and more as we go down to other else if right?.
gudii9Author Commented:
Hi gudii9

As you have x = 30 on top of your program after the main only the x == 30 code will be executed in both your programs hence you are getting the same output as you have the same print 30 statement there.

Please refer my comment  starting with below as it shows the way your code is executed
The execution is only the difference. We can get the same outputs with either statement

I f you only had

if( x == 30 ){ System.out.print("Value of X is 30");} in your 2nd Test program with out an else and if you put x = 40 in both then you will get This is else statement in your 1st program and no output in your 2nd test program.

can you please advise with example.

I ran as below and got same output

public class TestIfAndElseIfAndElseIfAndElseIf{

   public static void main(String args[]){
      int x = 40;

      if( x == 10 ){
         System.out.print("Value of X is 10");
      }else if( x == 20 ){
         System.out.print("Value of X is 20");
      }else if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("This is else statement");
      }
   }
}

Open in new window


public class TestIfAndIfAbdIf {
   public static void main(String args[]){
      int x = 40;

      if( x == 10 ){
         System.out.print("Value of X is 10");
      } if( x == 20 ){
         System.out.print("Value of X is 20");
      } if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("This is else statement");
      }
   }
}

Open in new window


This is else statement

but not
x = 40 in both then you will get This is else statement in your 1st program and no output in your 2nd test program.
Kanti PrasadCommented:
Hi gudii9

Both will be filtering and the operation to look for true is the same....
               the if will filter once as an individual statement and
              if else if else if else will filter multiple times within a block.


So if you have only one condition then you use if (x==10) {print ..; and do something .....}

and as you have multiple conditions  use if else if else if else

IF .. else if ... else if... else is block of execution so once it enters into it will be out the block  
    1. Once any condition is true ( in your code as x ==30 it will go pass 10, 20  and at 30 it is true) or
     2.  If you had x not equal 10 , 20 or 30 then it will go into the else and come out of the block.

I menat    if( x == 10 ){}else if( x == 20 ){}else if( x == 30 ){}else{} as one block

The advantage of the above is that even if you assign any new value to x  say 20 it will only be assigned only once it is out of the block fully.

So you will not have any issues if someone assign any new value to x in between any of the IF statements.

With an only if statements and you have 3 of them so if say at x = 10  you change the value of x to 20 once it is inside IF(x ==10)

IF(x==10){System.out.print("Value of X is 10"); x = 20;}

Then as the above is an individual statement execution and now x is assigned 20 it will go again into the next statement where IF(x==20) {System.out.print("Value of X is 20");}
This is the danger as it will mess up your final desired output.

So in your if else if else if else this will not happen as the entire block is executed  and not as individual statement

So even if you assign x==20 inside x ==10 as below the else IF (x==20) condition inside the if else if else if else will not be executed as it has gone inside the block as  x == 10 and even as you assigned x = 20 it will only change the value of x to 20 only after it comes out of the entire block.


int x = 30;
      if( x == 10 ){  System.out.print("Value of X is 10"); x =20; }
       else if( x == 20 ){ System.out.print("Value of X is 20"); }
      else if( x == 30 ){System.out.print("Value of X is 30"); }
       else  { System.out.print("This is else statement"); }

if you see krakatoa comments where he commented the *else*
to print 10 20 20  
and print 10 20  with  if else if else if else
so by commenting *else*  in else If he made those statement as individual statements instead of block execution so you have different results.

So that is the difference between use many  single if statements and if else if else if else block....

As you also see in the above code comments  you  can get your outputs by case or switch
 so you can do anyway you wish but when you do it you need to know how address pitfalls and work around them..
Kanti PrasadCommented:
Hi

As you have the below code and you are running them as individual if statements you will get the same output as when ever x <> 30 it will enter the else statement.

if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("This is else statement");


So even if you have 10 or 20 it will still go into x==30 and as it is not true it will go into the else statement. So this the danger for using individual if statements.


I meant you keep int x = 40 and don't use the else statement in your  2nd test program as below and execute both the programs

      if( x == 10 ){
         System.out.print("Value of X is 10");
      } if( x == 20 ){
         System.out.print("Value of X is 20");
      } if( x == 30 ){
         System.out.print("Value of X is 30");
      }
   }
}

The 1st test program will to to your else statement

and 2nd test program it will not give you an output as you did not address its true condition  x ==40.

So change the above in your 2nd test program and in your 1st test program out x = 40 below the main and you will see the difference
gudii9Author Commented:
when x is 40  

if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("This is else statement");//it comes and prints this



and then




when x is 40  

 if( x == 10 ){
         System.out.print("Value of X is 10");
      } if( x == 20 ){
         System.out.print("Value of X is 20");
      } if( x == 30 ){
         System.out.print("Value of X is 30");
      }if( x == 40 ){
         System.out.print("Value of X is 40");//it comes and prints this
      }
   }
}
gudii9Author Commented:
So this the danger for using individual if statements.

i did not understand what is the danger. please advise
gudii9Author Commented:
"If it rains, I will take my umbrella", else "if it snows, I will take my anorak", else "I will wear pyjamas". You wear pyjamas only if it neither rains nor snows.

i perfectly got this analogy.

what is analogy for multiple if statements. Please advise
gudii9Author Commented:
if(a)(doA();}
if(a)(doA();}
if(a)(doA();}
if(a)(doA();}
else if(1)(doX();}//why this is always get tested..for that matter all statements get tested right no mater if or else if ???
else(doZ();}
gudii9Author Commented:
"else if" means that if the first 'if' condition was not true, then test this one, and should that not apply either, then test any further "else if" statements.

and "else" after all that means 'do whatever I say here, whatever value x is that hasn't already been met'.

above bold part is not clear. Other part is clear.

please advise
Kanti PrasadCommented:
Hi

If (x==10) your single line statement;   or If (x==10) { your single line statement; }
no braces                                                          with braces

If there is one line statement braces{} are optional and omitting them is personal choice but the code is in danger as if a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.

if-then-else statement provides a secondary path i.e "if" clause evaluates to false then it goes into the esle to check that condition

Here is an example class
class IfElseDemo {
    public static void main(String[] args) {

        int testscore = 100;
        char grade;

        if (testscore >= 90) { grade = 'A';}
           else if (testscore >= 80) {grade = 'B';}
              else if (testscore >= 70) {grade = 'C';}
                else if (testscore >= 60) { grade = 'D';} else { grade = 'F';}
        System.out.println("Grade = " + grade);
    }
}
The output from the program is:

 as you put int testscore = 100   Grade = A

But we you see a 100 is greater all the conditions are true in all the if else if conditions but once and if condition with in an if else if else if else turns out to be true then  the other statements will not evaluated. This is the benefit of having if else if else if  else and also any assignment to say testscore = 75 will not be in effect till it comes out of that block.

In individual statements it will pass through all the conditions and all will be tested as it is true in all the cases and as each individual statement is a different line of code but with if else if else if  else it is one block.
               if (testscore >= 90) { grade = 'A';}
             if (testscore >= 80) {grade = 'B';}
              if (testscore >= 70) {grade = 'C';}
             if (testscore >= 60) { grade = 'D';}
So the danger with individual, statement is that if we re-assign a value to testscore = 75 it will take effect from the next line itself hence will do different things which will not happen in If else if else if as it is a block.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.