Conditional Statements
Introduction to Conditional Statements
Programs often need to make decisions based on conditions. Conditional statements allow your program to execute different code paths depending on whether certain conditions are true or false.
Basic If Statement:
// Simple conditional statement
System.out.println("Starting robot check...");
if (true) {
System.out.println("This code always runs!");
}
// Conditional with comparison
int batteryLevel = 85;
if (batteryLevel > 50) {
System.out.println("Battery level is sufficient");
}Code Blocks and Indentation
Conditional statements create code blocks enclosed by curly brackets
{}. Code inside blocks should be indented 4 spaces or 1 tab to improve readability.Proper Indentation:
int motorSpeed = 75;
// Correctly indented
if (motorSpeed > 50) {
System.out.println("High speed mode");
motorSpeed = 100;
}
// Incorrectly indented (avoid this)
if (motorSpeed > 50) {
motorSpeed = 100;
}Comparison Operators:
Essential Operators for Conditions:
>- Greater than>=- Greater than or equal to<- Less than<=- Less than or equal to==- Equal to!=- Not equal to
Comparison Examples:
int sensorReading = 255;
if (sensorReading != 0) {
System.out.println("Sensor detected something");
}
if (sensorReading >= 200) {
System.out.println("Strong signal detected");
}
if (sensorReading < 50) {
System.out.println("Weak signal");
}Else Statements
The
else statement provides an alternative code path when the if condition evaluates to false.If-Else Example:
int robotPosition = 45;
if (robotPosition > 50) {
System.out.println("Robot is in the forward zone");
} else {
System.out.println("Robot is in the back zone");
}
// Another example
double batteryVoltage = 11.5;
if (batteryVoltage >= 12.0) {
System.out.println("Battery voltage is good!");
} else {
System.out.println("Battery needs charging!");
}Multiple Conditions: else if
Use
else if to check multiple conditions in sequence. The first condition that evaluates to true will execute, and the rest will be skipped.Multiple Conditions:
int gameScore = 85;
if (gameScore == 100) {
System.out.println("Perfect score!");
} else if (gameScore >= 90) {
System.out.println("Excellent performance!");
} else if (gameScore >= 70) {
System.out.println("Good job!");
} else if (gameScore >= 50) {
System.out.println("Keep practicing!");
} else {
System.out.println("Need more work!");
}Order of Execution:
Important Rules:
- Conditions are checked from top to bottom
- Only the first true condition executes
- Once a condition is true, remaining conditions are skipped
- Place most specific conditions first
Execution Order Example:
int number = 15;
// This works correctly
if (number % 3 == 0 && number % 5 == 0) {
System.out.println("FizzBuzz"); // Divisible by both 3 and 5
} else if (number % 3 == 0) {
System.out.println("Fizz"); // Divisible by 3 only
} else if (number % 5 == 0) {
System.out.println("Buzz"); // Divisible by 5 only
} else {
System.out.println(number); // Not divisible by 3 or 5
}
// This would NOT work correctly:
// if (number % 3 == 0) would catch 15 first!Comparing Strings
Strings must be compared using the
.equals() method, not the == operator. The == operator compares object references, not the actual text content.String Comparison:
String robotStatus = "active";
String userInput = "ACTIVE";
// Correct way to compare strings
if (robotStatus.equals("active")) {
System.out.println("Robot is running");
}
// Case-insensitive comparison
if (userInput.equalsIgnoreCase("active")) {
System.out.println("User wants robot active");
}
// Comparing two string variables
String command1 = "forward";
String command2 = "backward";
if (command1.equals(command2)) {
System.out.println("Commands are the same");
} else {
System.out.println("Commands are different");
}
// Wrong way (don't do this)
if (robotStatus == "active") {
// This may not work as expected!
}Logical Operators
Combine multiple conditions using logical operators:
&& (AND), || (OR), and ! (NOT).Logical Operators:
Combining Conditions:
&&- AND (both conditions must be true)||- OR (at least one condition must be true)!- NOT (reverses the boolean value)
Examples:
// AND operator - both must be true
int speed = 50;
int temperature = 60;
if (speed >= 30 && temperature < 80) {
System.out.println("Safe to operate");
}
// OR operator - at least one must be true
boolean buttonA = true;
boolean buttonB = false;
if (buttonA || buttonB) {
System.out.println("A button was pressed");
}
// NOT operator - reverses the condition
boolean emergencyStop = false;
if (!emergencyStop) {
System.out.println("Normal operation");
}Logical Operator Truth Table:
// Truth table examples
boolean a = true;
boolean b = false;
System.out.println("=== AND (&&) Operation ===");
System.out.println("true && true = " + (true && true)); // true
System.out.println("true && false = " + (true && false)); // false
System.out.println("false && true = " + (false && true)); // false
System.out.println("false && false = " + (false && false)); // false
System.out.println("\n=== OR (||) Operation ===");
System.out.println("true || true = " + (true || true)); // true
System.out.println("true || false = " + (true || false)); // true
System.out.println("false || true = " + (false || true)); // true
System.out.println("false || false = " + (false || false)); // false
System.out.println("\n=== NOT (!) Operation ===");
System.out.println("!true = " + (!true)); // false
System.out.println("!false = " + (!false)); // trueTry It Yourself:
Exercise 1: Conditional Logic Practice
- Create a robot battery status checker with multiple levels
- Write a sensor range validator with proper error handling
- Implement a game mode selector using string comparisons
- Build a complex safety system using logical operators
Practice writing conditional statements for various scenarios: