📚

 > 

💻 

 > 

🖥

3.3 If-Else Statements

2 min readjune 18, 2024

Avanish Gupta

Avanish Gupta

Avanish Gupta

Avanish Gupta


AP Computer Science A 💻

130 resources
See Units

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
Remember to place brackets around all of the code that should run if the condition is true and brackets around all of the code that should run if the condition is false. Without brackets, the computer may get confused about what code it should run and do something you're not expecting. You can prevent a lot of headaches by remembering to add brackets around each body and indenting the code inside!

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); } }
Browse Study Guides By Unit
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
🖱Unit 10 – Recursion
🧐Exam Skills