Java Series: Part 3

Table of Contents

Java If-Else Statements — Make Your Code Think!

🧠 Part 3: If-Else in Java — Make Your Code Think for You

So far, you’ve learned how to store information with variables. Now it’s time to teach your code how to make decisions — like a brain!

🤔 What Is an If-Else Statement?

Imagine this:

If it’s raining, take an umbrella.
Else, wear sunglasses. 😎

This is how real-life decisions work — and Java can do the same!

javaCopyEditif (condition) {
  // do this
} else {
  // do that
}

🧪 Example: Basic If-Else

int age = 18;

if (age >= 18) {
System.out.println("You can vote!");
} else {
System.out.println("Sorry, too young to vote.");
}

✅ If the condition is true (age >= 18), it runs the first part
❌ If not, it runs the second part

🧩 How Conditions Work

Conditions are true or false questions. Here are the most common:

OperatorWhat It MeansExample
==Equalsage == 18
!=Not equalage != 18
>Greater thanscore > 100
<Less thanprice < 10
>=Greater than or equallives >= 1
<=Less than or equalspeed <= 5.0

🧠 Else If = More Options!

You can chain decisions using else if.

int temp = 30;

if (temp > 30) {
System.out.println("It's hot!");
} else if (temp >= 15) {
System.out.println("Nice weather.");
} else {
System.out.println("Brrr... it's cold.");
}

Java reads them top-down and picks the first one that’s true.

🎯 Real Example: Grading System

int score = 85;

if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("You need to study more!");
}

📌 Try changing the score to see how your program reacts.

🛠 Mini Challenge: Build a Mood Bot

Try writing a program that prints a message based on mood:

String mood = "happy";

if (mood.equals("happy")) {
System.out.println("Yay! Keep smiling 😊");
} else if (mood.equals("sad")) {
System.out.println("Sending you good vibes ❤️");
} else {
System.out.println("Mood not recognized 😐");
}

✅ Tip: Use .equals() for comparing String values.

⚠️ Quick Warnings for Beginners

  • Use == for numbers
  • Use .equals() for strings
  • Always open {} curly braces for blocks
  • Conditions must be true or false

🧭 What’s Next? (Part 4 Preview)

Now that your code can think, let’s make it loop! 🔁

In Part 4, we’ll cover:

➡ What is a loop?
➡ How to repeat actions using for and while
➡ Write a program that counts, loops through lists, or creates patterns

🔖 Java If-Else Cheat Sheet

if (condition) {
// runs if condition is true
} else if (anotherCondition) {
// runs if previous was false but this is true
} else {
// runs if all above are false
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Want to keep up with our blog?

Get our most valuable tips right inside your inbox, once per month!

Related Posts

0
Would love your thoughts, please comment.x
()
x