In this Java tutorial, you will learn how decision making statements control the flow of a program. Java uses if, if-else, if-else-if, and switch statements to run different blocks of code based on conditions.
Decision Making Statements in Java
Decision making in Java means choosing which statement or block of statements should run next. A condition is tested, and based on the result, the program takes one path or another.
Java supports the following commonly used conditional statements:
These statements are used whenever a program has to respond differently to different values, user inputs, calculation results, or object states.
How Conditions Work in Java Decision Making
Most decision making statements in Java use a condition that evaluates to a boolean value: either true or false. The condition is usually written with comparison operators, logical operators, or boolean variables.
Common operators used in Java conditions
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 10 |
!= | Not equal to | x != 0 |
> | Greater than | x > 5 |
< | Less than | x < 100 |
>= | Greater than or equal to | x >= 18 |
<= | Less than or equal to | x <= 60 |
&& | Logical AND | age >= 18 && age <= 60 |
|| | Logical OR | day == 6 || day == 7 |
! | Logical NOT | !isAvailable |
The condition inside an if or else if must be a boolean expression. Java does not treat numbers such as 0 or 1 as boolean values.
if (condition) {
// statements to execute when condition is true
}
1. If Statement
The if statement checks a condition and executes a block of code if that condition is true.
In the example below, we check if the variable x is positive. If it is, the program prints a message to the console that the given number is positive.
Main.java
public class Main {
public static void main(String[] args) {
int x = 10;
if (x > 0) {
System.out.println("x is positive.");
}
}
}
Output:
x is positive.
This program uses the if statement to check if x is greater than zero. Since x is 10, the condition is true and the message “x is positive.” is printed.
Use a plain if statement when there is no alternative action required for the false case.
2. If-Else Statement
An if-else statement provides an alternative block of code that executes when the condition is false.
In the following example, the program checks if x is positive. If the number is positive, the program prints a message from the if block. If the number is not positive, the program prints a message from the else block.
Main.java
public class Main {
public static void main(String[] args) {
int x = -2;
if (x > 0) {
System.out.println("x is positive.");
} else {
System.out.println("x is not positive.");
}
}
}
Output:
x is not positive.
Here, the if-else statement checks the condition for x. Since x is -2, the condition fails and the else block executes, printing “x is not positive.”
Use if-else when exactly one of two possible branches should run.
3. If-Else-If Statement
The if-else-if ladder lets you check multiple conditions in sequence. The program evaluates each condition in order until one of them is true, and then executes the corresponding block. If none of the conditions is met, the else block runs.
In this example, we check if x is positive, negative, or zero. We have set x to 0 so that the final else block executes.
Main.java
public class Main {
public static void main(String[] args) {
int x = 0;
if (x > 0) {
System.out.println("x is positive.");
} else if (x < 0) {
System.out.println("x is negative.");
} else {
System.out.println("x is zero.");
}
}
}
Output:
x is zero.
This program demonstrates the if-else-if ladder. It checks the value of x sequentially. Since x equals 0, none of the first two conditions are met and the else block executes, printing “x is zero.”
The order of conditions matters in an if-else-if ladder. Place the most specific condition before a broader condition when both could become true.
public class Main {
public static void main(String[] args) {
int marks = 82;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
}
}
Grade B
Here, marks >= 75 is tested after marks >= 90. This order correctly classifies 82 as Grade B. If the broadest condition were placed first, later grade checks may never run.
4. Switch-Case Statement
The switch statement evaluates a single expression and executes the matching case block. Each case is a possible value of the expression. If no case matches, the default block is executed. Remember to use break; to prevent fall-through between cases.
In the example below, the value of x is checked using a switch statement. Since x is 2, the corresponding case is executed.
Main.java
public class Main {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 0: {
System.out.println("x is zero.");
break;
}
case 1: {
System.out.println("x is one.");
break;
}
case 2: {
System.out.println("x is two.");
break;
}
default: {
System.out.println("default operation.");
}
}
}
}
Output:
x is two.
In this switch-case example, the program evaluates the value of x and matches it to the corresponding case. Since x is 2, the case for 2 executes and prints “x is two.” The break; statement stops further execution of the switch.
When to Use If-Else and When to Use Switch in Java
Both if-else and switch are decision making tools, but they fit different situations.
| Requirement | Better choice | Reason |
|---|---|---|
| Check a range such as age, marks, price, or temperature | if / if-else-if | Range comparisons need operators such as >, <, >=, or <=. |
| Choose based on one exact value | switch | Cases are easier to read when checking fixed values. |
| Combine multiple boolean conditions | if / if-else | Logical operators such as && and || are clearer in boolean expressions. |
| Choose based on menu option, day number, enum, or command | switch | The expression is matched against known choices. |
| Need only one optional action | if | No false branch is needed. |
As a general rule, use if-else-if when conditions involve ranges or complex boolean logic. Use switch when one expression is compared with a fixed list of possible values.
Nested Decision Making Statements in Java
A decision making statement can be placed inside another decision making statement. This is called nesting. Nested statements are useful when one condition should be checked only after another condition is true.
public class Main {
public static void main(String[] args) {
int age = 20;
boolean hasId = true;
if (age >= 18) {
if (hasId) {
System.out.println("Entry allowed");
} else {
System.out.println("ID required");
}
} else {
System.out.println("Entry not allowed");
}
}
}
Entry allowed
In this example, the program checks the age first. The ID check is performed only when the age condition is true.
Nested conditions are valid, but too many levels can make code difficult to read. When possible, use clear condition names, early returns inside methods, or separate helper methods to keep the logic readable.
Java Decision Making With Boolean Variables
A condition does not always need to be written as a comparison. If a variable is already of type boolean, it can be used directly in an if statement.
public class Main {
public static void main(String[] args) {
boolean isLoggedIn = true;
if (isLoggedIn) {
System.out.println("Show dashboard");
} else {
System.out.println("Show login page");
}
}
}
Show dashboard
This form is cleaner than writing if (isLoggedIn == true). For the opposite condition, use the NOT operator as if (!isLoggedIn).
Common Mistakes in Java Conditional Statements
- Using
=instead of==: Use==for comparison. The single equals sign is used for assignment. - Forgetting braces in multi-line blocks: Braces make the scope clear and help avoid accidental logic errors.
- Placing broad conditions before specific ones: In an
if-else-ifladder, the first true condition wins. - Forgetting
breakin a traditional switch: Withoutbreak, execution may continue into the next case. - Comparing strings with
==: Useequals()when you want to compare the contents of two strings.
String role = "admin";
if (role.equals("admin")) {
System.out.println("Admin access");
}
The expression role.equals("admin") compares the text stored in the string. This is usually what you need when making decisions based on string values.
Java Decision Making QA Checklist
Before finalizing a Java decision making example, review the logic with this checklist:
- Does every
ifandelse ifcondition evaluate totrueorfalse? - Are the conditions in an
if-else-ifladder ordered from specific to general where needed? - Does the
elseblock correctly handle the remaining cases? - Does a traditional
switchstatement includebreakwhere fall-through is not intended? - Are string comparisons written with
equals()instead of==? - Is the output checked with sample values that cover true, false, and default paths?
Frequently Asked Questions on Java Decision Making
What is decision making in Java?
Decision making in Java is the process of executing different blocks of code based on conditions. The condition is evaluated as true or false, and the program chooses the appropriate branch.
What are the main conditional statements in Java?
The main conditional statements in Java are if, if-else, if-else-if, and switch. They help a program handle different cases without running the same statements every time.
Which is better in Java: if-else or switch?
Use if-else when you need range checks or complex boolean expressions. Use switch when one expression must be matched against a fixed list of values such as menu choices, enum values, or day numbers.
Can we use multiple conditions in a Java if statement?
Yes. You can combine conditions using logical operators such as && for AND, || for OR, and ! for NOT. For example, age >= 18 && hasId checks two conditions together.
Is else required after every if statement in Java?
No. The else block is optional. Use else only when some alternate action should run when the if condition is false.
Summary of Java Decision Making Statements
In this Java tutorial, we learned how decision making statements help control program flow. The if statement runs a block only when a condition is true. The if-else statement chooses between two branches. The if-else-if ladder checks multiple conditions in order. The switch statement is useful when one expression must be matched against fixed values. Choosing the right conditional statement makes Java code easier to read, test, and maintain.
TutorialKart.com