You’ve learned about the basics of Java, how to store data using variables, different data types, and how to perform operations with operators. Now, it's time to learn how to make your programs smarter and more dynamic by introducing decision-making capabilities using conditional statements.
Imagine a real-world scenario: "If it's raining, I will take an umbrella. Otherwise, I won't." Or "If I have enough money, I will buy the car. If not, but I have enough for a bicycle, I'll buy that. Otherwise, I'll walk." Conditional statements allow your programs to mimic this kind of decision-making logic, executing different blocks of code based on whether certain conditions are true or false.
The if Statement
The if statement is the most basic form of a conditional statement. It executes a block of code only if a specified condition is true.
Syntax:
if (condition) {
// Code to be executed if the condition is true
}condition: This is a boolean expression (something that evaluates totrueorfalse).The code inside the curly braces
{}is called the "if block" or "if body".
Example:
public class IfStatementExample {
public static void main(String[] args) {
int score = 85;
if (score >= 60) {
System.out.println("Congratulations! You passed the exam.");
}
System.out.println("This message is always displayed.");
}
}In this example, since score (85) is indeed greater than or equal to 60, the message "Congratulations! You passed the exam." will be printed.
Important Note: If the if block contains only a single statement, the curly braces {} are optional, but it's good practice to always use them for clarity and to avoid potential errors, especially when adding more statements later.
The if-else Statement
The if-else statement allows your program to perform one action if the condition is true and a different action if the condition is false. It provides an alternative path for execution.
Syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}Example:
public class IfElseStatementExample {
public static void main(String[] args) {
int temperature = 25; // in Celsius
if (temperature > 30) {
System.out.println("It's a hot day! Stay hydrated.");
} else {
System.out.println("The weather is pleasant.");
}
int age = 17;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not yet eligible to vote.");
}
}
}In the first if-else, temperature is 25, which is not > 30, so the else block executes. In the second, age is 17, which is not >= 18, so the else block executes.
The if-else if-else Ladder
When you have multiple conditions to check sequentially, and you want to execute code for the first condition that evaluates to true, you use the if-else if-else ladder.
Syntax:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
} else {
// Code to be executed if none of the above conditions are true
}The conditions are evaluated from top to bottom. As soon as a condition is found to be true, its corresponding block of code is executed, and the rest of the ladder is skipped. If none of the if or else if conditions are true, the else block (if present) is executed.
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int grade = 75;
if (grade >= 90) {
System.out.println("Your grade is A");
} else if (grade >= 80) {
System.out.println("Your grade is B");
} else if (grade >= 70) {
System.out.println("Your grade is C");
} else if (grade >= 60) {
System.out.println("Your grade is D");
} else {
System.out.println("Your grade is F");
}
}
}For grade = 75, grade >= 90 is false. grade >= 80 is false. grade >= 70 is true, so "Your grade is C" is printed, and the rest of the ladder is skipped.
Nested if Statements
You can place an if statement inside another if or else block. This is called nesting. Nested if statements are used when you need to check a condition only after another condition has already been met.
Syntax:
if (outerCondition) {
// Code related to outerCondition being true
if (innerCondition) {
// Code related to both outerCondition AND innerCondition being true
} else {
// Code related to outerCondition true, but innerCondition false
}
} else {
// Code related to outerCondition being false
}Example:
public class NestedIfExample {
public static void main(String[] args) {
boolean hasDrivingLicense = true;
int age = 20;
if (hasDrivingLicense) {
System.out.println("You have a driving license.");
if (age >= 18) {
System.out.println("You are also old enough to drive legally.");
} else {
System.out.println("But you are not old enough to drive legally yet.");
}
} else {
System.out.println("You do not have a driving license.");
}
}
}The switch Statement
The switch statement provides an alternative to a long if-else if-else ladder when you are checking a single variable against multiple possible constant values. It can make your code cleaner and easier to read in such scenarios.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression matches value1
break; // Important: exits the switch block
case value2:
// Code to execute if expression matches value2
break;
// ... more cases
default:
// Code to execute if expression does not match any case values
// break; // Optional for the last default case
}expression: This is the value to be compared. In Java,expressioncan be of typebyte,short,int,char,String, or anenum.case value: These are constant values that theexpressionis compared against.break: Thebreakkeyword is crucial. It causes the program to exit theswitchblock once a match is found and its code is executed. Withoutbreak, the program will "fall through" and execute the code for subsequentcases until abreakis encountered or theswitchblock ends. This "fall-through" behavior is rarely desired.default: Thedefaultcase is optional. It specifies the code to be executed if none of thecasevalues match theexpression. It acts like theelseblock in anif-else if-elseladder.
Example:
public class SwitchStatementExample {
public static void main(String[] args) {
int dayOfWeek = 3; // 1 for Monday, 2 for Tuesday, etc.
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Today is " + dayName);
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Very Good!");
break;
case 'C':
System.out.println("Good.");
break;
case 'D':
System.out.println("Pass.");
break;
case 'F':
System.out.println("Fail.");
break;
default:
System.out.println("Invalid grade.");
}
}
}The Ternary Operator (Conditional Operator)
The ternary operator (? :) is a shorthand for a simple if-else statement that returns a value. It's often used for concise assignments.
Syntax:
variable = (condition) ? valueIfTrue : valueIfFalse;Example:
public class TernaryOperatorExample {
public static void main(String[] args) {
int number = 10;
String result;
result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(number + " is " + result);
int age = 22;
String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
System.out.println("You are " + eligibility + ".");
}
}Boolean Expressions Revisited
The "condition" within all conditional statements (like if, else if, and the ternary operator) must always evaluate to a boolean value (true or false). These conditions are typically formed using:
Relational Operators:
==(equal to)!=(not equal to)<(less than)>(greater than)<=(less than or equal to)>=(greater than or equal to)
Logical Operators:
&&(AND): Both conditions must be true.||(OR): At least one condition must be true.!(NOT): Reverses the boolean value.
Example of complex conditions:
int x = 10;
int y = 5;
boolean isValid = true;
if (x > y && isValid) { // true AND true = true
System.out.println("x is greater than y AND isValid is true");
}
if (x < y || !isValid) { // false OR false = false
System.out.println("This won't be printed");
}
Best Practices
Always use `{}` braces: Even for single-line `if` statements. It prevents errors and improves readability.
Use `switch` for clean code: It's a great choice when comparing one variable against multiple fixed values.
Don't forget `break`: In a `switch` statement, missing a `break` causes "fall-through," which is usually a bug.
Don't use `==` for floating-point numbers: Check if the difference is within a small tolerance instead.
Keep it readable: If a nested `if` statement becomes too complex, consider refactoring it into a separate method.
Consider readability: For very complex nested if statements, consider breaking them down into smaller, more manageable functions or redesigning the logic.
Boolean variables as conditions: You can directly use a boolean variable as a condition:
boolean isLoggedIn = true;
if (isLoggedIn) { // no need for if (isLoggedIn == true)
System.out.println("User is logged in.");
}
Key Takeaways
-
Conditional statements allow us to introduce decision-making into our programs
-
If, if-else, if-else if-else, nested if, and switch