...

/

Make Decisions

Make Decisions

Use conditional logic to control flow based on the input.

Now that Java can take input, let’s make it respond to that input. You’ll use if, else, and comparison operators in this lesson to help Java make decisions.

Goal

You’ll aim to:

  • Use if, else if, and else.

  • Compare numbers and strings.

  • Control logic based on conditions.

Execution of code depends on the condition being met
1 / 12
Execution of code depends on the condition being met

Note: Java lets you run different blocks of code depending on whether a condition is true or false. This is called conditional logic—it’s how programs make decisions.

The basic if statement

Let’s start with the most basic condition: the if statement. If the condition is true, the code inside the if block runs. Otherwise, Java moves on and skips that block.

Java
public class Main {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("A grade");
} else if (score >= 80) {
System.out.println("B grade");
} else {
System.out.println("Keep working on it!");
}
}
}

The program picks the matching path.

Nice work! You’ve written your first conditional. Now your code can make decisions.

Comparison operators

  • == equal to

  • != not equal to

  • > greater than

  • < less than

  • >= greater than or equal to

  • <= less than or equal to

Note: You’ll use the above if conditions to compare values.

Combine with input

Let’s combine what you’ve learned: use Scanner to get input and if to react to that input. Your program now makes choices based on what the user types.

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your age: ");
        int age = input.nextInt();

        if (age >= 18) {
            System.out.println("You're an adult.");
        } else {
            System.out.println("You're a minor.");
        }
    }
}
Comparison operators in Java

You're on fire! You just made your program respond differently depending on what the user typed. This is the foundation of smart software!