Dangling Else Problem in Java:
In the below example our objective is to check if the x value is greater than 5 and y value is greater than 10.For the given input of x=10 and x=4
public class HelloWorld{
public static void main(String []args){
int x=10;
int y=20;
if(x>5)
if(y>10)
System.out.println(“First case”);
else
System.out.println(“Second case”);
}
}
x=10
The output of the code:
$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
First case
x=4
$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
It is printing only the First case or no output at all. This is because of the dangling else problem. As the else part is closer to the second if, the JVM will treat this as part of the inner if. not the outer if. However, we can force the JVM to treat it differently by using a bracket.
public class HelloWorld{
public static void main(String []args){
int x=5;
int y=20;
if(x>15){
if(y>10)
System.out.println(“First case”);
}
else
System.out.println(“Second case”);
}
}
Now the output of the code is:
$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
Second case
if else if construction:
if the code is like below:
if(boolean-expression)
statement-1
else if(boolean-expression)
statement-2
else
statement-3
the JVM will treat this as:
if(boolean-expression)
statement-1
else if(boolean-expression)
statement-2
else
statement-3
It is kind of 3 way branching.
JVM will execute the first boolean-expression.If it is true,it will execute statement-1 and skips the remaining if conditions and go out of the if block.If the first expression is false it will execute the second boolean-expression and decide the statement-2 and statement-3.
The above could be modified as:
if(boolean-expression)
statement-1
else if(boolean-expression)
statement-2
else if
statement-3
In this way, it will become multiway branching.