computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🔀

🎓

⏱ 25 min

Free

Making Decisions

Use if, else if, else and logical operators to make your Java programs smart.

🎯 What you will learn

  • Write if / else if / else
  • Combine conditions with && and ||
  • Use switch for many choices

👋 Let’s get started!

Games decide things constantly: Did you hit the target? Is health zero? Let’s teach Java to decide. The ideas are the same as Python — only the punctuation changes! 🔀

🪜 Step by step

1. 🔀 if / else

The condition goes in ( ) and the code in { }.

int health = 0;
if (health <= 0) {
    System.out.println("Game over 💀");
} else {
    System.out.println("Keep going!");
}
2. 🔗 && and ||

&& means AND, || means OR.

boolean hasKey = true;
boolean doorNear = true;
if (hasKey && doorNear) {
    System.out.println("Door opened!");
}
3. 🎛️ switch

switch picks one of many options.

int day = 6;
switch (day) {
    case 6: System.out.println("Saturday 🎉"); break;
    case 7: System.out.println("Sunday 😴"); break;
    default: System.out.println("School day 📚");
}

🧪 Try it!

Read the code, guess what it prints, then press 👀 Show output.

Grade calculator

int score = 84;
if (score >= 90) {
    System.out.println("A 🌟");
} else if (score >= 80) {
    System.out.println("B 👍");
} else if (score >= 70) {
    System.out.println("C 🙂");
} else {
    System.out.println("Keep practicing 💪");
}

Can you ride?

int height = 130;
if (height >= 120) {
    System.out.println("Enjoy the ride! 🎢");
} else {
    System.out.println("Not yet!");
}

📖 Key words

Tap a card to flip it over!

if
Runs code when a condition is true ❓
&&
AND — both must be true 🤝
||
OR — at least one is true 🙋
switch
Chooses between many cases 🎛️

🏆 Challenge

Predict: what prints when temp is 15?

Challenge

int temp = 15;
if (temp > 25) {
    System.out.println("Hot");
} else if (temp > 10) {
    System.out.println("Nice");
} else {
    System.out.println("Cold");
}

Knowledge Check Quiz

  1. What does && mean?
  2. What prints?
  3. Where does the condition go?
← Previous lesson
Next lesson →