At times, we have an if statement, and then inside that if statement, we have multiple conditions to check, assuming the first condition in the outermost if statement is true. This is where nested conditionals help. This is as simple as placing a conditional statement inside another conditional statement. Here is how we can do this with the leap year code:
public static boolean isLeap(int year) {
if (year % 100 == 0) {
if (year % 400 == 0) {
return true;
}
return false;
} else if (year % 4 == 0) {
return true;
}
return false;
}
Here you can see why formatting your code with indentations and bracketing can make reading the code a lot easier. Imagine trying to find an issue in this code if there were no indents or brackets. You would likely have a hard time figuring out what is supposed to happen. And this is a relatively simple example without too many layers of nesting.
Before we return to the code above, we need to talk about boolean logical operators. These make up long compound boolean statements and are used to evaluate combinations of smaller boolean statements. There are three which we will learn in this course:
! (NOT) negates whatever is in front of it
&& (AND) returns true if BOTH the statement directly preceding it and the statement following it are true
|| (OR) returns true if at least one of the statements directly preceding or following it is true
There is an order of operations to these operators if there are multiple in one expression. The NOT operator has the highest precedence, followed by the AND operator and finally the OR operator.
Using these operators, we can combine multiple conditionals to clean up our code. However, this can lead to some complex boolean expressions... we'll learn how to simplify them in the next topic!
twoB || !twoB,
that is the question - Shakespeare
Using logical boolean operators, we can make compound conditional statements such as:
returns (a % 2 == 0) && (a % 3 == 0)
This returns whether a number is divisible by both 2 and 3. Compound conditional statements can eliminate the use of nested conditional statements. Here is the leap year method without nested conditionals:
public static boolean isLeap(int year) {
if (year % 400 == 0 || year % 4 == 0 && 100 != 0) {
return true;
}
return false;
}
Compare the leap year method with nested conditionals to the leap year method that uses compound conditional statements. As you can see, compound conditional statements can help make your code a lot more compact and readable. This means it will be easier to find issues within your code.