Making Multiple Decisions
Multiple Related Decisions
If you examine the code above, the second conditional statement uses both keywords of else if
. This is only possible because:
We have a trailing if statement on the same indentation level
We are writing a code that relies on checking multiple conditions
The conditions that we are checking are all related to each other
In the code above, the else if
's and else
's codes within its blocks will be ignored if the first condition evaluates to True. This occurs when age
is greater than or equal to 13.
The significant learning point is that the program will not check the next conditions if the first one was true. It will only try to check to other conditions if the prior conditions are false.
Multiple, but Unrelated Decisions
Code Explanation
The two if statements above are not related. Both conditions will evaluated no matter the result of the boolean expressions.
The bottom most else statement is only related to our second if statement. The program will not skip to the else statement if the
weather.equals("Yes")
evaluates to false.The program will output:
It is just a number.
if the variablenum
was not 42.
Nested Conditionals
Nested conditional statements in Java are simply conditional statements within another conditional statement.
Let's assume that variable num
has a value 45
.
We first check if
num
is greater than0
.If it is, we print that the number is positive, then we check if it's even or odd using another nested
if-else
statement.
If
num
is not greater than0
, we move to theelse if
part and check if it's less than0
. If it is, we print that the number is negative.If
num
is neither greater than0
nor less than0
, it must be0
, so we print that the number is zero.
Last updated