Java Tutorial Series: This lesson is part of our comprehensive Complete Java Tutorial: Learn Java from Beginner to Advanced.
Conditional Statements in Java: Conditions, Decisions and Examples
Introduction
Conditional statements are one of the foundations of Java programming. They allow a program to make a decision instead of executing every statement in exactly the same way. A program can check input, compare values, validate rules, control access, classify data and choose different actions depending on the situation.
For a beginner, conditional statements connect basic Java concepts such as variables, data types and operators with real program logic. Once conditions are understood, loops, methods, validation and larger application workflows become much easier to understand.
What Are Conditional Statements in Java?
A conditional statement evaluates a condition and chooses what code should execute based on the result. In Java, conditions are normally boolean expressions that produce either true or false.
int age = 21;
if (age >= 18) {
System.out.println("Eligible");
}
The expression age >= 18 is evaluated first. Because it is true, the statement inside the if block executes.
Why Conditional Logic Is Important
Almost every useful application contains decisions. A registration system may check whether a username is available. A banking application may check whether a balance is sufficient. An e-commerce application may decide whether a customer qualifies for a discount. A game may choose an action based on the player's state.
Without conditional logic, programs would have very limited ability to respond to changing data.
Conditions and Boolean Values
A condition can be a boolean variable or an expression that produces a boolean value.
boolean loggedIn = true;
if (loggedIn) {
System.out.println("Welcome");
}
Comparison operators are also commonly used:
int marks = 75;
boolean passed = marks >= 40;
The result of marks >= 40 is true, so passed becomes true.
The if Statement
The if statement executes a block only when its condition is true.
if (temperature > 30) {
System.out.println("Hot");
}
If temperature is 30 or less, Java skips the block. An if statement is useful when there is an action to perform only for one condition and no alternative action is required.
The if-else Statement
if-else provides two possible paths.
int balance = 500;
if (balance >= 1000) {
System.out.println("Requirement met");
} else {
System.out.println("Requirement not met");
}
Exactly one of these branches executes.
The else-if Ladder
An else-if ladder is useful when there are several possible outcomes.
int marks = 82;
if (marks >= 90) {
System.out.println("A+");
} else if (marks >= 75) {
System.out.println("A");
} else if (marks >= 60) {
System.out.println("B");
} else {
System.out.println("C");
}
Java evaluates the conditions from top to bottom and executes the first matching branch.
Nested Conditions
A condition can contain another condition.
if (age >= 18) {
if (hasId) {
System.out.println("Entry allowed");
}
}
Nested conditions can model dependent decisions, but too much nesting can make code difficult to read. When logic becomes complicated, consider moving it into a method or simplifying the conditions.
The switch Statement
switch is useful when one expression needs to be matched against several discrete choices.
int option = 2;
switch (option) {
case 1:
System.out.println("Create");
break;
case 2:
System.out.println("View");
break;
default:
System.out.println("Invalid option");
}
switch is covered in more detail in the dedicated Switch Statement article.
The Ternary Operator
The ternary operator provides a compact two-way decision.
String status = age >= 18 ? "Adult" : "Minor";
It is best suited to simple expressions. A normal if-else structure is usually easier to read when each branch contains several statements or complicated logic.
Combining Conditions
Logical operators allow multiple conditions to work together.
if (age >= 18 && hasId) {
System.out.println("Access granted");
}
Use && when all required conditions must be true, || when at least one condition can be true, and ! when a condition needs to be negated.
Condition Ordering and Boundaries
When checking ranges, the order of conditions matters. For example, when classifying marks, a condition for 90 or above should normally be checked before a condition for 75 or above. Otherwise, the broader condition may capture values that should have received the higher classification.
Boundary operators also matter. Decide deliberately whether a boundary should use > or >= and < or <=.
Common Conditional Statement Mistakes
Common mistakes include using = instead of ==, comparing strings incorrectly, reversing conditions, forgetting braces, creating overlapping ranges and adding unnecessary nesting.
Another common problem is writing a condition that does not cover an expected input. Testing boundary values such as 0, 1, 39, 40, 74, 75 and 90 can reveal these issues.
Practical Example: Eligibility
int age = 24;
boolean verified = true;
boolean active = true;
if (age >= 18 && verified && active) {
System.out.println("Eligible");
} else {
System.out.println("Not eligible");
}
This demonstrates how several business rules can be combined into one decision.
Conditional Logic and Program Design
As applications grow, conditions often represent business rules. Instead of creating one enormous if-else block, developers can separate rules into methods with descriptive names. This makes the program easier to test and maintain.
For example, a method such as isEligibleForDiscount() communicates intent more clearly than repeating a complicated expression throughout an application.
How to Debug Conditional Logic
When a condition produces an unexpected result, inspect the values being compared, evaluate each part separately, check operator precedence and test boundary values. Temporary print statements or a debugger can help reveal which branch is actually executing.
Best Practices
Use meaningful variable names, keep conditions readable, use braces consistently, avoid deeply nested decisions, test both true and false paths and extract complicated business rules into methods. Prefer clarity over writing the fewest possible lines.
Practice Exercises
1. Check whether a number is positive, negative or zero.
2. Determine whether a student passed or failed.
3. Classify marks into several grades.
4. Check whether a customer qualifies for a discount.
5. Determine whether a year is a leap year.
6. Build a simple login validation rule.
7. Create a menu using switch.
Frequently Asked Questions
What is a conditional statement in Java?
It is a control-flow structure that chooses which code executes based on a condition.
What type of value does a Java condition produce?
Normally a boolean value: true or false.
What should I learn after conditional statements?
Practice if-else, else-if and switch, then learn loops such as for, while and do-while.
Can conditions be combined?
Yes. Logical operators can combine multiple boolean expressions.
Conclusion
Conditional statements give Java programs decision-making ability. Start with simple if statements, then learn if-else, else-if, switch and ternary expressions. Practice boundary cases and real-world rules so that your conditions become reliable rather than merely syntactically correct.
Learn More
- Java Syntax
- Java Variables
- Java Data Types
- Java Operators
- Java Input and Output
- Java Methods
- Java Arrays and Collections
Continue Learning Java
After this topic, continue through the Java control-flow path by practicing the next related statement or loop. Build small programs rather than only reading examples.
Deeper Practical Coverage
Conditions, Expressions and Boolean Logic
A conditional statement is only as reliable as the condition it evaluates. In Java, conditions normally produce a boolean value, so understanding expressions is essential before writing larger decision structures. A condition can compare numbers, compare characters, check a boolean variable, call a method that returns boolean, or combine several smaller conditions.
For example, a validation rule can be represented as a single expression:
int age = 24;
boolean verified = true;
boolean active = true;
boolean eligible = age >= 18 && verified && active;
if (eligible) {
System.out.println("User can continue");
}
Naming a complicated condition can make the business rule easier to understand and test. It also prevents the same complicated expression from being copied into several branches.
Short-Circuit Evaluation
Java's && and || operators use short-circuit evaluation. With &&, Java stops evaluating when it already knows the complete expression must be false. With ||, Java stops when it already knows the complete expression must be true. This can improve efficiency, but it also matters for correctness when the second expression has a side effect or depends on the first expression.
For example:
if (user != null && user.isActive()) {
System.out.println("Active user");
}
The second condition is evaluated only when user is not null. This pattern is common in validation and defensive programming.
Guard Conditions and Early Returns
As methods grow, nested conditional blocks can make the main business path difficult to follow. A guard condition checks an invalid or exceptional state early and returns, throws, or otherwise exits the current operation.
For example:
static boolean canTransfer(boolean loggedIn, double balance, double amount) {
if (!loggedIn) {
return false;
}
if (amount <= 0) {
return false;
}
if (balance < amount) {
return false;
}
return true;
}
This can be easier to maintain than nesting the entire successful path inside several if statements.
Range-Based Decisions
Many real applications classify values into ranges: age groups, score bands, tax slabs, shipping tiers, risk levels, or temperature categories. Range conditions should be written carefully so that every intended value belongs to the correct category.
For example:
int score = 75;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 75) {
System.out.println("Good");
} else if (score >= 60) {
System.out.println("Average");
} else {
System.out.println("Needs improvement");
}
The order matters because once score >= 75 becomes true, later branches are not evaluated.
Testing Conditional Logic
A conditional structure should be tested systematically rather than with only one normal example. For a rule such as age >= 18, useful tests include 17, 18, and 19. For a score range, test every boundary and representative values inside each range.
A practical test checklist is:
– Normal valid value
– Minimum accepted value
– Maximum accepted value
– Just below a boundary
– Exactly at a boundary
– Just above a boundary
– Invalid value
– Missing or unexpected state where applicable
This approach catches many logic errors before the program reaches production.
Conditional Logic in Enterprise Applications
In larger Java systems, conditional logic appears in service methods, validation layers, controllers, authorization checks, payment workflows, order processing, feature flags, retry decisions, and event processing. A small if statement may be perfectly appropriate, but a very large conditional block can become difficult to test.
When the number of business rules grows, developers can separate rules into methods, enums, configuration, strategy implementations, or dedicated services. The goal is not to eliminate if statements. The goal is to keep decision logic understandable and changeable.
Decision Tables and Rule Thinking
Before implementing complicated business logic, it can help to write the rules as a small decision table. For example, an account operation might depend on whether the user is logged in, whether the account is active, and whether sufficient balance exists.
Thinking about the combinations first helps prevent missing cases. After the rules are clear, Java conditions can implement them. This is especially useful for validation and authorization code where an overlooked condition can create a functional or security problem.
Common Design Smells
Watch for repeated conditions, duplicated business rules, very deep nesting, branches containing hundreds of lines, and conditions that are difficult to explain in plain language. These patterns do not automatically mean the code is wrong, but they are signals that the decision logic may need refactoring.
A useful test is: can another developer explain what each branch represents without tracing the entire method? If not, extract named methods or simplify the rule structure.
Practice Scenario: Order Eligibility
Suppose an order should be accepted only when the customer is active, payment is verified, and the order total is positive.
boolean customerActive = true;
boolean paymentVerified = true;
double total = 1499.0;
if (customerActive && paymentVerified && total > 0) {
System.out.println("Order accepted");
} else {
System.out.println("Order requires review");
}
Now test each condition independently. This teaches an important professional habit: do not test only the successful path; test which individual rule causes rejection.
Extended Practice Set
- Write a program with three mutually exclusive ranges and test every boundary.
- Create an eligibility rule using four boolean conditions.
- Refactor a deeply nested decision into guard conditions.
- Write tests for both successful and rejected cases.
- Explain why the first matching else-if branch wins.
Java Language and Version Note
The Java platform documentation groups control flow into decision-making, looping, and branching constructs. Modern Java has also expanded switch with expression forms, arrow rules, and pattern-oriented capabilities. When publishing this article, the website should state the Java version when an example depends on a newer language feature. Core syntax such as if, if-else, for, while, do-while, break, continue, and traditional switch remains foundational, while newer forms should be presented as version-aware additions.