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.
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.
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!");
}
}
}
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 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.
if (condition) {
// code to execute if condition is true
}
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.");
}
}
}
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.
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.
if (condition) {
// code executed when condition is true
} else {
// code executed when condition is false
}
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.");
}
}
}
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.
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.
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
}
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.");
}
}
}
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.
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.
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.");
}
}
}
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 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.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block executed if no case matches
}
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);
}
}
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.
Understanding fall-through behavior is important, since forgetting a break statement is one of the most common mistakes beginners make when using switch statements.
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");
}
}
}
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 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. |
| 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. |
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.