if Statements and Control Flow
Overview: 3.2.0
- if statements (conditionals) change the flow of control through the program
- code is only run when something is true
- Otherwise the block is skipped
- code is only run when something is true
- conditionals use the keyword
if
followed by a boolean expression- if
(myvar==0)
- followed by statement or block of statements
- block statements enclosed by curly brackets
- if
boolean myvariable = true;
if (myvariable) {
System.out.println("This will only execute if myvariable has a value of true");
}
Relational Operators in if Statements: 3.2.1
- if statements can use relational operators for a boolean condition
==
,!=
,<
,>
,<=
,>=
int myInteger = 3;
int myOtherInt = 77;
if (myInteger == 3) {
System.out.println("my integer is 3");
}
if (myOtherInt > 50) {
System.out.println("My other int is greater than 50");
}
Common Errors: 3.2.2
- Always use curly brackets to enclose a block after the if statement
- Java doesn’t care about indentation
- Don’t use a semicolon after an if statement
- Use curly brackets
- Always use
==
, not=
Summary: 3.2.4
- if statements test a boolean expression
- Runs the following statement/block if it is true
- relational operators are used in boolean expressions to compare values and expressions
- if statements affect the flow of control by changing what code executes based on the value of a boolean
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.