new!###### πΆ

###### Cram Center

new!###### Study with Hours

Subjects and resources that you bookmark will appear here.

Light Mode

2 min readβ’november 16, 2020

Peter Cao

Caroline Koffke

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;
}
```

Before we return to the code above, we need to talk about **boolean logical operators**. These makeup 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 of the statements directly preceding or 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;
}
```

Take this quiz for a progress check on what youβve learned this year and get a personalized study plan to grab that 5!

START QUIZStudying with Hours = the ultimate focus mode

Start a free study sessionSign up now for instant access to 2 amazing downloads to help you get a 5

Browse Study Guides By Unit

π

Exam Reviews

π±

Unit 10: Recursion

β

Unit 1: Primitive Types

π±

Unit 2: Using Objects

π₯

Unit 3: Boolean Expressions and if Statements

πΉ

Unit 4: Iteration

βοΈ

Unit 5: Writing Classes

βοΈ

Unit 6: Array

πΎ

Unit 7: ArrayList

π»

Unit 8: 2D Array

π²

Unit 9: Inheritance

Thousands of students are studying with us for the AP Computer Science A exam.

join now