+ 1
What are the benefits nesting if-else inside if statement?
3 Respuestas
+ 3
Perhaps, an example will help:
if (gender == "male")
if (age >= 18)
System.out.println("He is an adult")
else
System.out.println("He is a child")
else
if (age >= 18)
System.out.println("She is an adult")
else
System.out.println("She is a child")
+ 2
I think the question is answered very well by the example of Igor Berger.
It would be very chaotic putting the whole query on an if statement of the first degree.
When youre NOT using nested if statements it would be look like:
If (gender == "male" && age >= 18)
{
System.out.println ("He is an adult");
}
else if (gender == "male" && age < 18)
{
System.out.println ("He is a child");
}
else if (gender == "female" && age >= 18)
{
System.out.println ("She is an adult");
}
else if (gender == "female" && age < 18)
{
System.out.println ("She is a child");
}
(I related to the example of Igor Berger)
As you see in my "bad example" it is very confusing and harder getting a fast overview of your queries.
Furthermore it is 'easier' for errors to sneak in.
This is, why you better use nested if - conditions.
0
when u use just else, every cases diferent to the condition will return the same result. when u use if-else you choose what the conditional should return in some cases when the condition is false.