###### Bookmarks

Subjects and resources that you bookmark will appear here.

Light Mode

The AP Computer Science A 5-hour live stream review is here!Β π»

Join us on May 5, 2021 for the πΆοΈ AP Computer Science A Cram Finale for a last minute review to get all your questions answered!

π

All Subjects

Β >Β

π»Β

AP Comp Sci A

Β >Β

π₯

Unit 3

# 3.3 If-Else Statements

Peter Cao

Caroline Koffke

## 3.3: If-Else Statements

We have just covered if statements, but what if we want something to be done if the condition that we are checking is false? This is where the else statement comes into play. The header for the else does not have a condition and is just "else" while the body is what is performed if the condition for the if statement is false.
Together, these create an if-else statement, or a two-way selection. Here is the anatomy of an if-else statement:
```some code that runs before conditional statement if (condition) { code that runs if the condition is true } else { code that runs if the condition is false } some code that runs after```

### Example: Number Rounding

Remember the rounding we learned in 1.5? Now with an if-else statement, we can finally write a method that implements this as follows:
```public static int round(double number) { if (number >= 0) { return (int) (number + 0.5); } else { return (int) (number - 0.5); } }```

##### πͺπ½ Are you ready for the Comp Sci exam?
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 QUIZ
Studying with Hours = the ultimate focus mode
Start a free study session
##### FREE AP comp sci a Survival Pack + Cram Chart PDF
Browse Study Guides By Unit
π
Exam Reviews
π±
Unit 10: Recursion
β
Unit 1: Primitive Types
π±
Unit 2: Using Objects
πΉ
Unit 4: Iteration
βοΈ
Unit 5: Writing Classes
βοΈ
Unit 6: Array
πΎ
Unit 7: ArrayList
π»
Unit 8: 2D Array
π²
Unit 9: Inheritance