Here's an example:
if ( num > 0 ) // Outer if if ( num < 10 ) // Inner if System.out.println( "num is between 0 and 10" ) ;There is an outer if statement, and an inner if.
What does Java do when it runs this code?
if ( num > 0 && num < 10 ) System.out.println( "num is between 0 and 10" ) ;
if ( num > 0 ) // Outer if { System.out.println( "Got here" ) ; if ( num < 10 ) // Inner if System.out.println( "num is between 0 and 10" ) ; }In this case, the if body of the outer if contains two statements, one of which is the inner if body.
This can't be rewritten using && because the first println() statement only depends on the outer condition.
What happens if an if statement appears in the else body?
if ( num > 90 ) { System.out.println( "You earned an A" ) ; } else if ( num > 80 ) { System.out.println( "You earned a B" ) ; }The statement "You earned a B" only if the outer ifcondition evaluates to false and the inner if condition evaluates to true. In other words, the first if condition has to "fail" before it's even possible that the second println() prints.
The first condition failing means that num is not greater than 90, so it must be less than or equal to 90. The second condition succeeding means that num is greater than 80. Combine the two and you get num greater than 80, but less than or equal to 90.
We can add yet another if statement to the else body, to take this one step further.
if ( num > 90 ) { System.out.println( "You earned an A" ) ; } else if ( num > 80 ) { System.out.println( "You earned a B" ) ; } else if ( num > 70 ) { System.out.println( "You earned a C" ) ; }In this case, you don't see "You earned a C" unless the top condition fails (i.e. num > 90), and the middle condition fails (i.e. num > 80), but the bottom condition succeeds (i.e. num > 70).
If you combine all the conditions together need to print "You earned a C", you get something that is less than or equal to 80, and greater than 70.
You should notice that this kind of structure goes through each condition one at a time. When it reaches the first condition that evaluates to true, it runs the body, and then skips everything else.
This is called a prioritized if. We'll see this more in an upcoming lesson.
if ( num > 0 ) if ( num < 10 ) if ( num % 2 == 0 ) System.out.println( "num is between 0 and 10 and even" ) ;As mentioned earlier, you can often use logical operators to avoid some forms of nesting.