Making Decisions: If Statements and Nested Logic
In programming, your code needs to be able to make choices. Should the user be allowed to log in? Is the game over? These decisions are handled by If Statements.
1. The Basic if Statement
An if statement tells Java: "Only run this code if this condition is true."
if (condition) {
// Code to run if true
}
Example:
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
}
2. Adding else and else if
What if the condition is false? You can use else to provide an alternative, or else if to check multiple conditions in order.
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
How it works: Java checks from top to bottom. As soon as it finds a true condition, it runs that block and skips the rest.
3. Nested if Statements
A Nested If is simply an if statement inside another if statement. Use this when a second decision depends entirely on the first one being true.
Example: Security Check
boolean hasTicket = true;
boolean passedSecurity = false;
if (hasTicket) {
System.out.println("Ticket verified. Proceed to security.");
if (passedSecurity) {
System.out.println("Welcome to the concert!");
} else {
System.out.println("Security check failed. You cannot enter.");
}
} else {
System.out.println("No ticket found. Please go to the box office.");
}
4. Comparison Operators
To create conditions, you'll need these symbols:
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | x == 5 |
!= |
Not equal to | x != 0 |
> |
Greater than | x > 10 |
< |
Less than | x < 20 |
>= |
Greater than or equal to | x >= 18 |
<= |
Less than or equal to | x <= 100 |
💻 Full Practical Example: Login System
Copy this code to see how nested logic works with user input:
import java.util.Scanner;
public class LoginSystem {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Username: ");
String user = input.nextLine();
if (user.equals("admin")) { // Note: Use .equals() for Strings!
System.out.print("Enter Password: ");
int pass = input.nextInt();
if (pass == 1234) {
System.out.println("Access Granted. Welcome, Admin.");
} else {
System.out.println("Incorrect Password.");
}
} else {
System.out.println("Unknown User.");
}
input.close();
}
}
⚠️ Common Pitfall: == vs .equals()
- For Numbers (
int,double), use==. - For Text (
String), always use.equals().- ✅
if (name.equals("YourName")) - ❌
if (name == "YourName")(This can lead to unpredictable bugs in Java!)
- ✅
💡 Challenge: The Number Classifier
Write a program that asks for a number and tells the user:
- If the number is Positive, Negative, or Zero.
- If it is positive, use a nested if to check if it is Even or Odd.