Unit 3: Boolean Expressions and If Statements
The if Statement in AP CS A
Introduction to the if Statement
In computer programming, decisions based on conditions are pivotal. The if statement in Java allows for the execution of code blocks based on the evaluation of certain conditions as true or false.
Syntax of the if Statement
The foundational syntax is:
if (condition) {
// Execute this code if condition is true
}
Where the condition is a Boolean expression.
How to Use the if Statement
Basic Usage
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5.");
}
Takeaway
If number is greater than 5, the console will display the message. If not, the program will bypass the if block.
Curly Braces {}: An Essential Component
Though if statements can be written without {} for single lines, it's a best practice to always include them to prevent potential pitfalls and enhance code clarity.
Single Line if Without {}
if (number > 5)
System.out.println("Number is greater than 5.");
Beware
When omitting {} with multiple statements after an if, only the immediate next line is treated as part of the if block. This can cause unforeseen behaviors.
Nested if Statements: An Advanced Concept
An if statement can be placed within another, known as nesting.
Nested Usage
int number = 15;
if (number > 10) {
System.out.println("Number is greater than 10.");
if (number < 20) {
System.out.println("Number is less than 20.");
}
}
Nested if Insight
In this example, the inner if is only evaluated when the outer if (number > 10) is true.
In Conclusion
Mastering the if statement is essential for anyone learning Java, as it's a foundational construct that provides much of the logical capabilities of a program. Remember to practice and stay vigilant for common pitfalls, especially around curly braces and nested conditions.
Additional Resources
AP CSA Homework Assignment
Assignment
Instructions
- Craft a Java application prompting the user to input their age.
- Use an if statement to evaluate if the user's age is below 18.
- If under 18, print "You are not an adult.".
- Otherwise, print "You are an adult.".
Ensure to test for edge cases and validate your program across different inputs for robustness.