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
  • 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
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