Skip to main content

3.3 Conditional Logic

Conditional logic is essential for decision-making in Java. You'll learn how to control the flow of your program using if, else, and switch statements, as well as how to use if-else chains for more complex conditions.

Key Topics:

  • The if Statement: Execute code blocks based on true conditions.
  • The else Statement: Define an alternative path when the condition is false.
  • The if-else Chain: Handle multiple conditions with sequential checks.
  • The switch Statement: Handle multiple conditions with minimal code.

Why i should use Conditional Logic in Java?

Conditional logic in Java is crucial for creating dynamic and responsive applications. It allows you to:

Customize user experiences: Tailor interactions based on user behavior or data. Implement security measures: Validate input and restrict access to sensitive features. Control application flow: Guide execution based on conditions, ensuring correct behavior. Enable feature toggling: Manage application features based on user roles or other criteria. By using conditional logic effectively, you can create more robust, user-friendly, and secure Java applications.

public class OnlineStore {
public static void main(String[] args) {
double totalOrderValue = 150.0; // Example total order value

// Simple if statement: Determine if the order qualifies for free shipping
if (totalOrderValue >= 100) {
System.out.println("Order qualifies for free shipping!");
}

// If-else statement: Calculate shipping cost based on order value
if (totalOrderValue < 50) {
double shippingCost = 10.0;
System.out.println("Shipping cost: $" + shippingCost);
} else {
double shippingCost = 5.0;
System.out.println("Shipping cost: $" + shippingCost);
}

// Else-if ladder: Apply tiered shipping rates based on order value
if (totalOrderValue < 25) {
double shippingCost = 15.0;
System.out.println("Shipping cost: $" + shippingCost);
} else if (totalOrderValue < 50) {
double shippingCost = 10.0;
System.out.println("Shipping cost: $" + shippingCost);
} else {
double shippingCost = 5.0;
System.out.println("Shipping cost: $" + shippingCost);
}

// Nested if statement: Apply discount if order is placed during a sale
boolean isSaleActive = true;
if (isSaleActive && totalOrderValue > 100) {
double discount = 10.0;
System.out.println("Discount applied: $" + discount);
}
}
}

The if Statement

The if statement is used to execute a block of code only if a specified condition is true. This allows your program to make decisions and respond to different situations dynamically.

Syntax:

if (condition) {
// Code to execute if the condition is true
}

Example:

int x = 10;
if (x > 5) {
System.out.println("x is greater than 5"); // This will execute because the condition is true
}

The else Statement

The else statement is used to define an alternative code block that will be executed if the condition in the if statement is false.

Syntax:

if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

Example:

int x = 10;
if (x > 15) {
System.out.println("x is greater than 15");
} else {
System.out.println("x is less than or equal to 15"); // This will execute because the condition is false
}

The if-else Chain

For cases where you need to check multiple conditions, you can use an if-else chain. This allows for sequential evaluation of conditions until one is met.

Syntax:

if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the conditions are true
}

Example:

int score = 85;

if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
Note:

Always use else if for multiple conditions instead of separate if blocks, as the latter checks every condition even if an earlier one is true. This can lead to inefficient code.

The switch Statement

The switch statement in Java allows you to evaluate an expression and execute the corresponding block of code based on the value of that expression.

Syntax:

switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
default:
// Default code if none of the above cases match
break;
}

Example:

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");
break;
}

Enhanced Switch (Java 12 and Above)

Starting from Java 12, you can use an enhanced version of the switch statement that simplifies syntax and returns values.

Example:

int day = 2;
String result = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Invalid day";
};
System.out.println(result);

Analogy: Traffic Lights

Analogy:

Think of if-else chains like traffic lights:

  • If the light is green (if condition is true), you move forward.
  • If the light is yellow (else if condition), you slow down and prepare to stop.
  • If the light is red (else condition), you stop.

This sequence ensures you make the right decision based on the current condition.

Conclusion

Mastering conditional logic in Java is crucial for building dynamic and responsive programs. By understanding if, else, if-else chains, and switch, you can guide the flow of your program to make the right decisions based on the conditions at hand.

By applying these techniques, you can build flexible, maintainable code that adapts to various situations.