If statements

Intermediate Java

Jim White

Java Developer

Control flow

If the condition is true ✅ ➡ do something

If the condition is false ❌ ➡ do nothing

Intermediate Java

How if statements work

If score is 90+ ➡ print "Great job!"

If score is less than 90 ➡ don't print it

Intermediate Java

if statement anatomy

if (condition) {
  // Code to run
}

If the condition is true, the code inside curly brackets runs

Intermediate Java

Conditions

  • Use comparison operators like =, !=, >, <, >=, <=, ...
// Print "Great job!" if score is >= 90
if (score >= 90) {
  System.out.println("Great job!");  
}
Intermediate Java

if and if and if ...

int score = 94;

if (score >= 90) {
  System.out.println("Excellent!");  
}

if (score >= 70) {
  System.out.println("Good job!");  
}

if (score < 70) {
  System.out.println("Try again!");  
}
Excellent!
Good job!
  • Both messages get displayed because the two conditions are satisfied
Intermediate Java

Recap

We can have different conditions, if they evaluate to true /false

if (score != 0){
  System.out.println("Well, you got some points!");
}

if (message.equals("F")){
  System.out.println("Try again!");
}

if (testResult == 100) {
  System.out.println("Wow, you got it all!");
}
Intermediate Java

Let's practice!

Intermediate Java

Preparing Video For Download...