Introduction to Decision-Making in Java
Course: Core Java Training
Topic: Introduction to Decision-Making in Java
Course Link: Core Java Training Course
Demo Link: Register for a Free Course Demo
Website: JustAcademy
1. Introduction to Decision-Making in Java
Decision-making is a fundamental programming concept that allows a Java program to choose which statements to execute based on specified conditions. Instead of executing every statement sequentially, a program can evaluate a condition and follow a particular path depending on whether the condition is true or false.
Java provides decision-making statements such as if, if-else, else-if ladder, nested if, and switch. These statements help developers implement business rules, validate user input, check eligibility, calculate discounts, and control application behavior.
Example: Checking Voting Eligibility
public class VotingEligibility {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
}
}
Output:
You are eligible to vote.
Explanation: The program checks whether age is greater than or equal to 18. Since the condition is true, the message is displayed.
2. Why Is Decision-Making Important?
Without decision-making statements, a program would generally execute instructions in sequence without choosing different actions according to changing data. Decision-making makes programs dynamic, interactive, and capable of responding to different situations.
- Conditional execution: Executes code only when a particular condition is satisfied.
- Validation: Checks whether user input meets specified requirements.
- Business logic: Implements rules such as discounts, eligibility, and payment status.
- Error prevention: Helps detect invalid values before performing operations.
- Application control: Allows programs to respond differently to different inputs.
- Improved flexibility: Enables the same program to handle multiple scenarios.
3. How Decision-Making Works in Java
Decision-making generally involves three steps: evaluating a condition, determining whether it is true or false, and executing the appropriate block of code.
- A variable or expression provides the data to evaluate.
- A condition is formed using comparison or logical operators.
- Java evaluates the condition as a Boolean value:
true or false.
- The decision-making statement selects the appropriate execution path.
- The program continues with the statements that follow the decision block.
Example
public class DecisionFlow {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("Positive number");
}
System.out.println("Program completed");
}
}
Output:
Positive number
Program completed
The first message is displayed because number > 0 evaluates to true. The final message executes after the if statement regardless of the condition.
4. Boolean Conditions in Decision-Making
Java decision-making statements use Boolean expressions to determine which code should run. A Boolean expression produces either true or false.
| Expression |
Result |
Explanation |
10 > 5 |
true |
10 is greater than 5. |
10 < 5 |
false |
10 is not less than 5. |
10 == 10 |
true |
Both values are equal. |
10 != 10 |
false |
The values are not different. |
age >= 18 |
Depends on age |
Checks whether the age is at least 18. |
marks >= 40 |
Depends on marks |
Checks a minimum passing score. |
5. Operators Commonly Used in Decision-Making
5.1 Relational Operators
Relational operators compare two values and return a Boolean result.
| Operator |
Meaning |
Example |
> |
Greater than |
age > 18 |
< |
Less than |
price < 100 |
>= |
Greater than or equal to |
marks >= 40 |
<= |
Less than or equal to |
quantity <= 10 |
== |
Equal to |
number == 5 |
!= |
Not equal to |
status != 0 |
5.2 Logical Operators
Logical operators combine or reverse Boolean conditions.
| Operator |
Meaning |
Example |
&& |
Logical AND; both conditions must be true. |
age >= 18 && hasId |
|| |
Logical OR; at least one condition must be true. |
isWeekend || isHoliday |
! |
Logical NOT; reverses a Boolean value. |
!isAvailable |
Example: Combining Conditions
public class AdmissionCheck {
public static void main(String[] args) {
int age = 21;
boolean hasIdentityCard = true;
if (age >= 18 && hasIdentityCard) {
System.out.println("Entry permitted");
} else {
System.out.println("Entry not permitted");
}
}
}
Output:
Entry permitted
Both conditions are true, so the program permits entry. If either condition were false, the combined AND expression would be false.
6. Types of Decision-Making Statements in Java
Java offers several decision-making structures. The correct choice depends on the number of conditions, the complexity of the logic, and whether the program is selecting between alternatives or matching a value against several cases.
| Statement |
Purpose |
Typical Use |
if |
Executes a block when a condition is true. |
Checking eligibility. |
if-else |
Selects between two alternatives. |
Pass or fail. |
else-if ladder |
Checks multiple conditions in sequence. |
Grade calculation. |
Nested if |
Places one conditional statement inside another. |
Multi-stage validation. |
switch |
Selects among alternatives based on a matching value or supported pattern. |
Menu selection. |
| Ternary operator |
Chooses one of two expressions. |
Simple value selection. |
7. The if Statement
The if statement executes a block of code only when its condition evaluates to true. If the condition is false, the block is skipped.
Syntax
if (condition) {
// Statements executed when the condition is true
}
Example: Checking a Positive Number
public class PositiveNumber {
public static void main(String[] args) {
int number = 15;
if (number > 0) {
System.out.println("The number is positive.");
}
}
}
Output:
The number is positive.
If number were zero or negative, the message inside the if block would not execute.
8. The if-else Statement
The if-else statement provides two execution paths. Java executes the if block when its condition is true; otherwise, it executes the else block.
Syntax
if (condition) {
// Executes when true
} else {
// Executes when false
}
Example: Pass or Fail
public class ExamResult {
public static void main(String[] args) {
int marks = 35;
if (marks >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Output:
Fail
Since 35 is less than 40, the condition is false and the else block executes.
9. The else-if Ladder
An else-if ladder evaluates several conditions in order. The first condition that evaluates to true determines the block that runs. If none is true, an optional final else block executes.
Syntax
if (condition1) {
// First block
} else if (condition2) {
// Second block
} else if (condition3) {
// Third block
} else {
// Default block
}
Example: Grade Calculation
public class GradeCalculator {
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 >= 60) {
System.out.println("Grade C");
} else if (marks >= 40) {
System.out.println("Grade D");
} else {
System.out.println("Fail");
}
}
}
Output:
Grade B
The value 82 does not meet the first condition, but it meets marks >= 75, so Grade B is displayed.
Important: Arrange ranges carefully. For example, placing marks >= 40 before marks >= 75 would cause a mark of 82 to match the earlier condition, preventing the intended higher-grade check.
10. Nested if Statements
A nested if statement is an if statement placed inside another conditional block. It is useful when one condition should be checked only after another condition has been satisfied.
Example: Login Validation
public class LoginValidation {
public static void main(String[] args) {
boolean usernameValid = true;
boolean passwordValid = true;
if (usernameValid) {
if (passwordValid) {
System.out.println("Login successful");
} else {
System.out.println("Invalid password");
}
} else {
System.out.println("Invalid username");
}
}
}
Output:
Login successful
The program first checks the username. Only if it is valid does it evaluate the password condition. This example demonstrates conditional flow; real authentication must verify credentials securely on a trusted server.
11. The switch Statement
The switch statement is useful when a program needs to select an action based on the value of an expression. Traditional switch statements commonly use supported integral types, their wrappers, char, String, and enum values. Supported switch expressions and patterns depend on the Java version.
Syntax
switch (expression) {
case value1:
// Statements
break;
case value2:
// Statements
break;
default:
// Default statements
}
Example: Day Selection
public class DaySelector {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output:
Tuesday
The value of day matches case 2. The break statement exits the switch block so execution does not continue into the following cases.
Understanding default and break
case defines a possible matching value.
break exits a traditional switch statement.
default provides a fallback when no case matches.
- Without
break, traditional switch execution may continue into later cases. This is known as fall-through.
Modern Switch Expression
Java 14 finalized switch expressions, which allow a switch to produce a value. Arrow-style cases do not fall through into the next case.
public class ModernSwitch {
public static void main(String[] args) {
int day = 2;
String dayType = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Invalid day";
};
System.out.println(dayType);
}
}
Output:
Weekday
Here, dayType receives the value produced by the matching switch branch.
12. The Ternary Operator
The ternary operator, written as condition ? expression1 : expression2, is a compact way to select one of two expressions. It is an operator rather than a decision-making statement, but it is commonly used for simple conditional assignments.
Syntax
result = condition ? valueIfTrue : valueIfFalse;
Example
public class TernaryExample {
public static void main(String[] args) {
int age = 17;
String status = age >= 18 ? "Adult" : "Minor";
System.out.println(status);
}
}
Output:
Minor
Use the ternary operator for short, readable choices. Prefer an ordinary if-else statement when the logic contains multiple steps or becomes difficult to understand.
13. Decision-Making with User Input
Java programs often use decision-making statements with user-provided values. The Scanner class can read console input, and conditional statements can evaluate the entered data.
Example: Checking a Number Entered by the User
import java.util.Scanner;
public class NumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
if (number > 0) {
System.out.println("Positive number");
} else if (number < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
scanner.close();
}
}
Example Output:
Enter an integer: -8
Negative number
This program uses three possible paths. The user enters an integer, and the program determines whether it is positive, negative, or zero. In production programs, invalid input should also be handled appropriately.
14. Decision-Making and Short-Circuit Evaluation
Java's logical AND (&&) and logical OR (||) operators use short-circuit evaluation. This means Java may skip evaluating the second condition when the first condition already determines the result.
Example: Safe Null Check
public class ShortCircuitExample {
public static void main(String[] args) {
String name = null;
if (name != null && name.length() > 0) {
System.out.println("Name is available");
} else {
System.out.println("Name is missing or empty");
}
}
}
Output:
Name is missing or empty
Because name != null is false, Java does not evaluate name.length() > 0. This prevents a null-pointer error in this particular condition.
15. Common Mistakes in Java Decision-Making
| Mistake |
Why It Is a Problem |
Correct Approach |
Using = instead of == for comparison. |
= assigns a value rather than checking equality. |
Use == for primitive equality comparisons. |
Adding a semicolon immediately after if (condition). |
The conditional statement may control an empty statement, leaving the following block unconditional. |
Write the block directly after the condition. |
| Incorrect condition order in an else-if ladder. |
A broad condition may match before a more specific one. |
Check the ranges from the most restrictive or highest-priority condition first. |
Forgetting break in a traditional switch. |
Execution may fall through into subsequent cases. |
Add break where fall-through is not intended, or use arrow-style cases. |
Using & instead of && for Boolean short-circuit logic. |
& does not short-circuit. |
Use && when the second condition should run only if the first is true. |
| Writing deeply nested conditions unnecessarily. |
Complex logic becomes harder to read and maintain. |
Use clear conditions, early returns where appropriate, or refactor into methods. |
| Ignoring invalid input. |
Unexpected values may cause incorrect behavior or runtime exceptions. |
Validate input and handle errors explicitly. |
16. Best Practices for Decision-Making
- Use meaningful variable names such as
isEligible, hasPermission, and isAvailable.
- Keep conditions simple and easy to understand.
- Use curly braces for conditional blocks, even when they contain only one statement.
- Arrange
else-if conditions so that more specific cases are not blocked by broader conditions.
- Choose
switch for clear multi-branch value selection and if-else for ranges or complex Boolean conditions.
- Use
&& and || when short-circuit behavior is appropriate.
- Test boundary values such as 0, 18, 39, 40, 74, and 75 where those values define decision thresholds.
- Validate data from users and external sources before making important decisions.
- Avoid excessive nesting and extract complicated rules into well-named methods.
- Write tests for true conditions, false conditions, and unexpected input.
17. Practical Example: Discount Calculator
This example demonstrates how decision-making can implement a simple business rule. Customers receive different discounts depending on the purchase amount.
public class DiscountCalculator {
public static void main(String[] args) {
double purchaseAmount = 6500;
double discountRate;
if (purchaseAmount >= 5000) {
discountRate = 0.20;
} else if (purchaseAmount >= 2000) {
discountRate = 0.10;
} else {
discountRate = 0.0;
}
double discount = purchaseAmount * discountRate;
double finalAmount = purchaseAmount - discount;
System.out.println("Purchase Amount: " + purchaseAmount);
System.out.println("Discount: " + discount);
System.out.println("Final Amount: " + finalAmount);
}
}
Output:
Purchase Amount: 6500.0
Discount: 1300.0
Final Amount: 5200.0
Explanation: Since the purchase amount is at least 5000, the first condition sets the discount rate to 20%. The program calculates the discount and subtracts it from the original purchase amount.
18. Practice Exercises
- Positive, Negative, or Zero: Write a program that accepts an integer and identifies whether it is positive, negative, or zero.
- Even or Odd: Use the remainder operator (
%) and an if-else statement to check whether a number is even or odd.
- Voting Eligibility: Accept a person's age and display whether they meet the minimum age requirement of 18.
- Largest of Two Numbers: Compare two integers and print the larger value, or indicate if both are equal.
- Largest of Three Numbers: Use an else-if ladder or nested conditions to find the largest of three values.
- Grade Calculator: Accept marks from 0 to 100 and assign grades using clearly defined ranges. Reject values outside the valid range.
- Simple Calculator: Use a switch statement to perform addition, subtraction, multiplication, or division based on a selected operator.
- Leap Year Checker: Apply the leap-year rules using relational and logical operators.
- Discount Calculator: Assign discounts according to purchase amount and calculate the final bill.
- Login Validation: Use Boolean conditions to demonstrate validation flow, without storing or exposing real passwords in sample output.
19. Interview Questions and Answers
Q1. What is decision-making in Java?
Answer: Decision-making is the process of selecting which statements a program should execute based on conditions. Java supports this through constructs such as if, if-else, else-if ladders, nested if, and switch.
Q2. What is the difference between if and if-else?
Answer: An if statement executes its block only when its condition is true. An if-else statement provides two alternatives: one for a true condition and another for a false condition.
Q3. When should you use an else-if ladder?
Answer: Use an else-if ladder when several conditions must be checked in order and only the first matching branch should execute.
Q4. What is a nested if statement?
Answer: A nested if is a conditional statement inside another conditional statement. It is useful when a later condition should be checked only after an earlier condition has been satisfied.
Q5. What is the purpose of the default case in a switch statement?
Answer: The default case provides a fallback action when none of the switch cases matches the supplied value. It is optional.
Q6. What is the difference between == and =?
Answer: The = operator assigns a value, while == compares primitive values for equality. For objects, == compares references rather than checking logical equality; methods such as equals() are commonly used for content comparison when appropriate.
Q7. What is the ternary operator?
Answer: The ternary operator is a compact conditional operator written as condition ? expression1 : expression2. It evaluates the condition and produces one of the two expressions' values.
Q8. What is short-circuit evaluation?
Answer: Short-circuit evaluation means Java skips evaluating the second operand of && when the first operand is false and skips the second operand of || when the first operand is true.
Q9. Can a switch statement handle multiple cases with the same result?
Answer: Yes. Multiple labels can lead to the same result. In modern arrow-style switch expressions, labels can be combined, for example case 1, 7 -> "Weekend";.
Q10. How can you make decision-making code easier to maintain?
Answer: Use descriptive names, readable conditions, appropriate statement types, curly braces, boundary tests, and small methods for complex business rules. Avoid unnecessary nesting and duplicated logic.
20. Quick Revision Checklist
- Decision-making lets a program select execution paths based on conditions.
- Conditions evaluate to Boolean values:
true or false.
if executes a block only when a condition is true.
if-else selects between two alternatives.
- An else-if ladder checks multiple conditions in order.
- Nested
if statements place conditional logic inside another condition.
switch selects among supported matching values or cases.
- The ternary operator is useful for simple conditional expressions.
- Relational and logical operators are frequently used to construct conditions.
- Good condition ordering, validation, and boundary testing help prevent logic errors.
21. Conclusion
Decision-making is one of the most important foundations of Java programming. It allows programs to respond intelligently to data and user input instead of following a fixed sequence of instructions. By learning if, if-else, else-if ladders, nested conditions, switch, Boolean expressions, and the ternary operator, beginners can implement practical logic for validation, grading, pricing, menus, and many other applications.
Practice these statements with different inputs, including boundary values and invalid data, to develop strong problem-solving skills and prepare for more advanced Java concepts.
Explore more learning opportunities through the JustAcademy Core Java Training Course, visit the course demo registration page, or browse the JustAcademy website.