πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

πŸ–₯

3.3 If-Else Statements

2 min readβ€’june 18, 2024

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 3 – Boolean Expressions & if Statements
πŸ•Ή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

Fiveable
Fiveable
Home
Stay Connected

Β© 2024 Fiveable Inc. All rights reserved.


Β© 2024 Fiveable Inc. All rights reserved.