07 Java Fundamentals | If-else statements in Java | By Dummy for Dummies

Java If-Else | Hassan Bukhari
Java Notes

07 Java Fundamentals | If-else statements in Java | By Dummy for Dummies

Java Beginner Guide If-Else Conditionals Decision Making

INTRODUCTION

Welcome back learners! It is indeed true that monkeys love bananas? But do they drink bananas? Nope. Depending on situations they consume different products. Our program that we code should be able to take different paths based on situations. For that purpose we write if-else statements in our code. These statements make our programs able to take decisions.


IF ELSE STATEMENTS

They check a condition, if it is true, they execute a specific part of code. If the condition is not true, an alternative part of code is executed.

  • if → Runs a code inside it when a condition is true
  • else → Runs an alternative code when condition is false
Java
public class Main {
    public static void main(String[] args) {
        int bananas = 12;
        if (bananas > 10) {
            System.out.println("We have enough bananas!");
        } else {
            System.out.println("We are short on bananas");
        }
    }
}
Console Output
We have enough bananas!

This will print We have enough bananas! because the condition we set is true (12 > 10).


With "else if"

Most of the time there are more than 2 possible outcomes. Therefore we have else if in these statements which add more conditions to block of code.

Java
public class Main {
    public static void main(String[] args) {
        boolean condition1 = false;
        boolean condition2 = false;
        boolean condition3 = false;

        if (condition1) {
            // If condition 1 is true execute this block of code
        } else if (condition2) {
            // If condition 2 is true execute this block of code
        } else if (condition3) {
            // If condition 3 is true execute this block of code
        } else {
            // If none of conditions is true execute this default block
        }
    }
}
Console Output
(No output - none of the conditions were true)

POINTS TO REMEMBER

⦿ Only one of these statements will be executed
⦿ If one condition is executed, the remaining are automatically ignored by Java even if they are true
⦿ If multiple conditions are true, only the first one is executed
⦿ If none are true, then else will always execute
⦿ Condition does the operations and returns boolean value (true or false)
⦿ Use comparison operators to form conditions (==, !=, >, <, >=, <=)
⦿ Use logical operators to combine multiple conditions (&&, ||, !)
⦿ The else block is optional; you can write just if and on returning false, nothing will happen
⦿ The else does not take a condition, but else if takes a condition

KEY LOGIC BUILDING

Write the most specific condition on top, and most common or overlapped on bottom. This way your program will have clean and neat logic. Here is a demonstration:

Java
public class Main {
    public static void main(String[] args) {
        int marks = 85;

        if (marks > 90) {      // Most specific, highest grade
            System.out.println("A");
        } else if (marks > 80) { // Next level
            System.out.println("B");
        } else if (marks > 70) {
            System.out.println("C");
        } else {
            System.out.println("Fail");
        }
    }
}
Console Output
B
  • 85 is not greater than 90 so first one is ignored
  • 85 is greater than 80 so second one is executed
  • Even though 85 is greater than 70, the program ignores the rest
  • Conditions are checked from top to bottom, so write most specific on top
  • Most specific means the one that overlaps the least with others (90 in this case)
  • else is not compulsory, but use it as a safety net. If all conditions fail, else guarantees a final outcome

"NESTED" IF ELSE STATEMENTS

Sometimes one question leads to more questions, like one decision leads to taking more decisions. In that case we use more if-else statements inside one.

Java
public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean hasID = true;

        if (age >= 18) {
            if (hasID) {
                System.out.println("You can enter the club.");
            } else {
                System.out.println("You need an ID to enter.");
            }
        } else {
            System.out.println("You are too young to enter.");
        }
    }
}
Console Output
You can enter the club.

Because the first condition returns true. And inside nested if, the other condition comes true as well, therefore we get that specific output.


EXTRA

To check if a condition is true, you can write it like: if(condition == true) or just if(condition)

To check if a condition is false, you can write it like: if(condition == false) or just if(!condition)


EXERCISE

Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.

Java
import java.util.Scanner;

public class IfElseExercise {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("=== IF-ELSE EXERCISE ===");
        System.out.print("Enter your marks (0-100): ");
        int marks = input.nextInt();

        System.out.print("Do you have good attendance? (true/false): ");
        boolean attendance = input.nextBoolean();

        // --- Simple if-else ---
        if (marks >= 50) {
            System.out.println("You passed the exam!");
        } else {
            System.out.println("You failed the exam!");
        }

        // --- if-else-if ladder ---
        if (marks >= 90) {
            System.out.println("Grade: A");
        } else if (marks >= 80) {
            System.out.println("Grade: B");
        } else if (marks >= 70) {
            System.out.println("Grade: C");
        } else if (marks >= 60) {
            System.out.println("Grade: D");
        } else {
            System.out.println("Grade: F");
        }

        // --- Nested if-else ---
        if (marks >= 50) {
            if (attendance) {
                System.out.println("You are eligible for a certificate!");
            } else {
                System.out.println("You passed, but no certificate due to poor attendance.");
            }
        } else {
            System.out.println("You must retake the exam.");
        }

        // --- Logical operators inside if ---
        if (marks >= 80 && attendance) {
            System.out.println("Excellent! You qualify for a scholarship.");
        } else if (marks >= 80 || attendance) {
            System.out.println("Good effort, but no scholarship.");
        } else {
            System.out.println("Work harder next time.");
        }

        input.close();
    }
}
Console Output
=== IF-ELSE EXERCISE === Enter your marks (0-100): 85 Do you have good attendance? (true/false): true You passed the exam! Grade: B You are eligible for a certificate! Excellent! You qualify for a scholarship.

MINI PROJECT: Grade Calculator

Your project is to create a simple Java program that calculates a student's grade based on percentage.

The program should ask the user to enter a percentage (0–100). According to the percentage entered, it should decide the grade using these rules:

  • 90–100 → Grade A
  • 80–89 → Grade B
  • 70–79 → Grade C
  • 60–69 → Grade D
  • Below 60 → Grade F

If the percentage entered is less than 0 or greater than 100, the program should print "Invalid Input."

Finally, the program should print the percentage and the calculated grade in a neat format.

While writing the program, make sure you use:

  • Scanner for input
  • If-Else statements for conditions
  • Relational and logical operators where needed
  • printf with placeholders like %d, %.2f, and %s

EXAMPLE OUTPUT

Console Output
Enter your percentage (0-100): 87 Your percentage: 87% Your grade: B

CLOSING

That's it for if-else statements in Java! They're the foundation of decision-making in programming. Once you understand how to set conditions and control the flow, you'll see how powerful even the simplest programs can become.