CS Engineering Gyan

Conditional Statements in Java

Programs rarely follow a single fixed path from start to finish. In most real-world situations, a program needs to make decisions based on the data it receives, and then behave differently depending on the outcome of those decisions. This ability to choose between different paths of execution is made possible through conditional statements.

Java provides several types of conditional statements, each suited to different kinds of decision-making scenarios. Some are designed for simple true-or-false checks, while others help organize multiple related conditions in a cleaner, more readable way.

In this tutorial, you will learn how the if statement works, how to build more complex decision structures using if-else and nested conditions, and how the switch statement offers an alternative approach for handling multiple possible values.


What is a Conditional Statement?

A conditional statement allows a program to execute a specific block of code only when a particular condition is true. If the condition evaluates to false, that block of code is skipped, and the program continues with whatever comes next.

Example

public class ConditionExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 105000;

        if (subscribers >= 100000) {

            System.out.println(channel + " has crossed one lakh subscribers!");

        }

    }

}

Output

CS Engineering Gyan has crossed one lakh subscribers!

In this example, the message is only displayed because the condition inside the parentheses evaluates to true. If the subscriber count were lower than the target, nothing would be printed at all.


The if Statement

The if statement is the most basic form of decision-making in Java. It evaluates a condition, and if that condition is true, the code inside the block runs. If the condition is false, the block is simply skipped.

Syntax

if (condition) {

    // code to execute if condition is true

}

Example

public class SimpleIfExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int videoLength = 15;

        if (videoLength > 10) {

            System.out.println(channel + " uploaded a long-form video.");

        }

    }

}

Output

CS Engineering Gyan uploaded a long-form video.

The if statement is useful when you only need to react to one specific condition, without needing an alternative action if that condition turns out to be false.


The if-else Statement

Often, a program needs to perform one action when a condition is true and a different action when it is false. This is where the if-else statement becomes useful, allowing two possible outcomes to be handled cleanly.

Syntax

if (condition) {

    // code executed when condition is true

} else {

    // code executed when condition is false

}

Example

public class IfElseExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 87000;

        if (subscribers >= 100000) {

            System.out.println(channel + " has reached the milestone.");

        } else {

            System.out.println(channel + " is still growing towards the milestone.");

        }

    }

}

Output

CS Engineering Gyan is still growing towards the milestone.

This structure ensures that exactly one of the two blocks will always execute, depending on whether the condition is true or false, making it useful for situations with two clearly defined outcomes.


The else-if Ladder

Sometimes a program needs to check several conditions in sequence, rather than just two. Java allows this through an else-if ladder, where multiple conditions are evaluated one after another until one of them is found to be true.

Syntax

if (condition1) {

    // executes if condition1 is true

} else if (condition2) {

    // executes if condition2 is true

} else {

    // executes if none of the above conditions are true

}

Example

public class ElseIfExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 52000;

        if (subscribers >= 100000) {

            System.out.println(channel + " has reached one lakh subscribers.");

        } else if (subscribers >= 50000) {

            System.out.println(channel + " has crossed fifty thousand subscribers.");

        } else {

            System.out.println(channel + " is still building its audience.");

        }

    }

}

Output

CS Engineering Gyan has crossed fifty thousand subscribers.

Java checks each condition from top to bottom and stops as soon as it finds one that is true. This means the order in which conditions are written can significantly affect the outcome, especially when ranges overlap.


Nested if Statements

A nested if statement is simply an if statement placed inside another if or else block. This structure is useful when a decision depends on more than one related condition being checked in stages.

Example

public class NestedIfExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 105000;

        boolean monetizationEnabled = true;

        if (subscribers >= 100000) {

            if (monetizationEnabled) {

                System.out.println(channel + " is eligible for premium partnerships.");

            } else {

                System.out.println(channel + " has crossed subscribers but monetization is disabled.");

            }

        } else {

            System.out.println(channel + " has not yet reached the required subscriber count.");

        }

    }

}

Output

CS Engineering Gyan is eligible for premium partnerships.

Nested conditions can become difficult to read if used excessively, so it is often a good idea to combine conditions using logical operators when possible, instead of deeply nesting multiple if statements.


The switch Statement

The switch statement provides an alternative way to handle multiple possible values of a single variable, especially when there are many specific cases to check. Instead of writing a long else-if ladder, a switch statement organizes each possibility into a separate case.

Syntax

switch (expression) {

    case value1:

        // code block

        break;

    case value2:

        // code block

        break;

    default:

        // code block executed if no case matches

}

Example

public class SwitchExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int dayNumber = 3;

        String uploadTopic;

        switch (dayNumber) {

            case 1:

                uploadTopic = "Java Basics";

                break;

            case 2:

                uploadTopic = "Data Structures";

                break;

            case 3:

                uploadTopic = "Object-Oriented Programming";

                break;

            default:

                uploadTopic = "General Programming Tips";

        }

        System.out.println(channel + " upload topic today: " + uploadTopic);

    }

}

Output

CS Engineering Gyan upload topic today: Object-Oriented Programming

The break statement is important inside a switch block, as it prevents execution from continuing into the next case after a match is found. Without it, Java would continue executing every case below the matching one, a behavior known as fall-through.


Switch Statement Fall-Through Behavior

Understanding fall-through behavior is important, since forgetting a break statement is one of the most common mistakes beginners make when using switch statements.

Example

public class FallThroughExample {

    public static void main(String[] args) {

        int rating = 2;

        switch (rating) {

            case 1:

                System.out.println("Needs Improvement");

            case 2:

                System.out.println("Average Content");

            case 3:

                System.out.println("Great Content");

                break;

            default:

                System.out.println("Invalid Rating");

        }

    }

}

Output

Average Content

Great Content

Since there is no break statement after case 2, execution continues into case 3 as well, printing both messages instead of just one. Adding a break after each case prevents this unintended behavior.


if-else vs switch Statement

if-else Statement switch Statement
Works well with complex conditions and ranges of values. Works best when comparing a single variable against fixed values.
Can evaluate multiple different variables in one structure. Typically evaluates only one variable or expression.
May become harder to read with many conditions. Often more organized and readable for many discrete cases.
Supports relational and logical operators directly. Primarily matches exact values rather than ranges.

Best Practices for Conditional Statements


Common Mistakes Beginners Make

Mistake Correct Practice
Using the assignment operator (=) instead of the equality operator (==) in a condition. Always use == when comparing values inside an if statement.
Forgetting the break statement in a switch case. Add a break after each case unless fall-through behavior is intentional.
Writing overlapping conditions in an else-if ladder in the wrong order. Arrange conditions logically, usually from the most specific to the most general.
Nesting too many if statements instead of combining conditions. Use logical operators like && and || to simplify nested conditions.

Frequently Asked Interview Questions

  1. What is the purpose of a conditional statement in Java?
    It allows a program to execute different blocks of code based on whether a condition is true or false.
  2. What is the difference between if and if-else statements?
    An if statement runs code only when a condition is true, while if-else also defines an action for when the condition is false.
  3. How does an else-if ladder work?
    Java checks each condition in order and executes the block for the first one that evaluates to true.
  4. What is a nested if statement?
    It is an if statement placed inside another if or else block to check additional related conditions.
  5. What is the purpose of the break statement in a switch block?
    It stops execution from continuing into the next case after a match is found.
  6. What happens if a break statement is missing in a switch case?
    Execution falls through and continues running the code in the following cases as well.
  7. When should you prefer a switch statement over if-else?
    Switch is preferable when comparing a single variable against several fixed, known values.
  8. What is the role of the default case in a switch statement?
    It executes when none of the defined cases match the given value.

Summary

Conditional statements give Java programs the ability to make decisions and respond differently based on the data they process. Starting with the simple if statement, moving through if-else structures, else-if ladders, and nested conditions, Java offers flexible tools for handling almost any decision-making scenario.

The switch statement provides an additional, often cleaner alternative when a single variable needs to be compared against multiple fixed values, though it requires careful attention to break statements to avoid unintended fall-through behavior. Together, these tools form the foundation for building programs that can adapt intelligently to different situations and inputs.

With a solid understanding of decision-making in Java, you are now ready to explore loops, which allow a program to repeat a block of code multiple times based on a given condition.


← Previous: Input & Output Next: Loops in Java →

Home Visit Our YouTube Channel