Is there any difference between writing multiple if
statements and if-else-if
statements ?
When I tried to write a program with multiple if
statements, It did not give the expected results, But it worked with if-else-if
.
The conditions were mutually exclusive.
When you write multiple if statements, it's possible that more than one of them will be evaluated to true, since the statements are independent of each other.
When you write a single if else-if else-if ... else statement, only one condition can be evaluated to true (once the first condition that evaluates to true is found, the next else-if conditions are skipped).
You can make multiple if statements behave like a single if else-if .. else statement if each of the condition blocks breaks out of the block that contains the if statements (for example, by returning from the method or breaking from a loop).
For example :
public void foo (int x)
{
if (x>5) {
...
return;
}
if (x>7) {
...
return;
}
}
Will have the same behavior as :
public void foo (int x)
{
if (x>5) {
...
}
else if (x>7) {
...
}
}
But without the return statements it will have different behavior when x>5 and x>7 are both true.
No both are not same.
if statements will check all the conditions. If you will write multiple if statement it will check every condition.
If else will check conditions until it is satisfied. Once if/else if is satisfied it will be out of that block.
Yes, it makes a difference: see The if-then and if-then-else Statements.
Furthermore, you can easily test it.
Code #1:
int someValue = 10;
if(someValue > 0){
System.out.println("someValue > 0");
}
if(someValue > 5){
System.out.println("someValue > 5");
}
Will output:
someValue > 0
someValue > 5
While code #2:
int someValue = 10;
if(someValue > 0){
System.out.println("someValue > 0");
}else if(someValue > 5){
System.out.println("someValue > 5");
}
Will only output:
someValue > 0
As you can see, code #2 never goes to the second block, as the first statement (someValue > 0) evaluates to true
.
if()
{
stmt..
}
else
{
stmt
}
if()
{
stmt
}
here compiler will check for both the if condition.
In below fragement of code compiler will check the if conditions, as soon as first if condition get true remaining if condition will be bypass.
if(){
}
else if
{
}
else if
{
}
else if
{
}