Forum

Learn Java If Then …
 
Notifications
Clear all

Learn Java If Then Else statements

1 Posts
1 Users
0 Reactions
15 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

🤖 What is an if-then-else statement in Java?

In Java, if-then-else statements allow your program to make decisions. It’s like giving your code a brain to choose different paths based on conditions.

📦 Basic Structure

if (condition) {
    // Code runs if condition is true
} else {
    // Code runs if condition is false
}

🧠 How it works

  • The condition inside the parentheses must evaluate to a boolean (true or false)
  • If true, the code block under if runs
  • If false, the else block runs instead

🔍 Example

int score = 85;

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

In this case:

  • If score is 90 or more, it prints “Excellent!”
  • Otherwise, it prints “Keep trying!”

🎯 Adding else if for more choices

if (score >= 90) {
    System.out.println("Excellent!");
} else if (score >= 75) {
    System.out.println("Good job!");
} else {
    System.out.println("Keep trying!");
}

Now there are three possible outcomes based on the value of score.


 


   
Quote
Share: