What are the benefits nesting if-else inside if statement? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What are the benefits nesting if-else inside if statement?

29th Jan 2017, 1:58 PM
Romario Kisku
Romario Kisku - avatar
3 Answers
+ 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")
29th Jan 2017, 5:44 PM
Igor B
Igor B - avatar
+ 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.
16th Feb 2017, 6:56 AM
Philipp Brandin
Philipp Brandin - avatar
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.
22nd Feb 2017, 10:52 PM
matias alonso
matias alonso - avatar