0

Why we use else if we can do same work using if statement. like

int x=35; if (x<14) { system.out.print("14" ); } system.out.print("nope"); will show same result (while using ELSE or without ELSE)

28th Jun 2017, 5:05 AM
Narayan K
Narayan K - avatar
4 Answers
+ 4
no not same result no matter how much x is nope will always printed
28th Jun 2017, 5:13 AM
Hetbo.net
Hetbo.net - avatar
+ 2
That is not correct, "nope" will now always be printed. Even if x < 14
28th Jun 2017, 5:10 AM
LaserHydra
LaserHydra - avatar
+ 2
They're not the same. With your code above System.out.print("nope"); is always printed. If you use an else statement it will only be printed if x is not less than 14. Without else: int x=10; if (x<14) { System.out.println("10" ); // This will be output. } System.out.println("nope"); // This will also be output. With else: int x=10; if (x<14) { System.out.println("10" ); // This will be output. } else { System.out.println("nope"); // This will NOT be output. }
28th Jun 2017, 5:14 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
All these answers are great, I'd just like to give you some extra info. Here's an example that would not make a difference if else or else if is used: int x = 34; if(x < 34) { // do something } if(x > 34) { // do something } if(x == 34) { // do something } In this case, why should I do something like this?: if(x < 34) { } else if(x > 34) { } else { } Well, one benefit from the else if statement is that it will not evaluate the condition unless the above if statement was false. The else also does not need to evaluate any condition. Because of this, simply using the else if and else makes things faster and is much less error prone. Errors can easily arrive if the variable was changed in a previous if statement. This is because the if statement after the others will still be evaluated. For example/ int x = 33; if(x < 34) { x += 10; } if(x > 34) { // This will now run! Making else if mandatory. }
28th Jun 2017, 5:41 AM
Rrestoring faith
Rrestoring faith - avatar