Conditional Basics
Introduction to Conditional Statements
Conditional statements are fundamental control flow mechanisms in Java that allow programmers to make decisions and execute different code blocks based on specific conditions. They enable dynamic program behavior by evaluating boolean expressions and selecting appropriate execution paths.
Basic Conditional Operators
Java provides several conditional operators to create complex decision-making logic:
Operator |
Description |
Example |
== |
Equal to |
x == y |
!= |
Not equal to |
x != y |
> |
Greater than |
x > y |
< |
Less than |
x < y |
>= |
Greater than or equal to |
x >= y |
<= |
Less than or equal to |
x <= y |
If-Else Statements
The most common conditional structure in Java is the if-else statement:
public class ConditionalExample {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are an adult");
} else {
System.out.println("You are a minor");
}
}
}
Nested Conditionals
Conditionals can be nested to handle more complex decision-making scenarios:
public class NestedConditionalExample {
public static void main(String[] args) {
int score = 75;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 70) {
System.out.println("Good");
} else if (score >= 60) {
System.out.println("Satisfactory");
} else {
System.out.println("Need improvement");
}
}
}
Logical Operators
Logical operators allow combining multiple conditions:
graph TD
A[Logical AND &&] --> B[Both conditions must be true]
C[Logical OR ||] --> D[At least one condition must be true]
E[Logical NOT !] --> F[Negates the condition]
Example of logical operators:
public class LogicalOperatorExample {
public static void main(String[] args) {
int x = 10;
int y = 20;
if (x > 0 && y < 30) {
System.out.println("Both conditions are true");
}
if (x > 100 || y < 30) {
System.out.println("At least one condition is true");
}
}
}
Ternary Operator
The ternary operator provides a compact way to write simple if-else statements:
public class TernaryOperatorExample {
public static void main(String[] args) {
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status);
}
}
Best Practices
- Keep conditional logic simple and readable
- Avoid deep nesting of conditionals
- Use meaningful variable and condition names
- Consider using switch statements for multiple conditions
By mastering these conditional basics, you'll be able to create more dynamic and intelligent Java programs. LabEx recommends practicing these concepts to improve your programming skills.