Skip to content

Week 6 - Conditions

Java Conditions

Learning Objectives

  1. Understand the Concept of Conditionals: Ensure students understand the basic concept of conditionals, which allow a program to make decisions based on certain conditions.
  2. Introduction to Boolean Values: Introduce the boolean data type and explain how it represents true or false values, which are essential for conditionals.
  3. If Statements: Teach students how to use the if statement to execute a block of code when a specified condition is true.
  4. Else Statements: Explain how to use the else statement to execute a block of code when the if condition is false.
  5. Else-If Statements: Introduce the else if statement to handle multiple conditions and provide alternatives when the initial if condition is false.
  6. Nested Conditionals: Show how to nest conditional statements within each other to create more complex decision-making structures.
  7. Switch Statements: Teach students how to use the switch statement to select one of many code blocks to execute based on the value of a single expression.
  8. Logical Operators: Explain the logical operators (&&, ||, !) and how they can be used to combine and manipulate boolean expressions in conditionals.
  9. Comparative Operators: Introduce comparative operators (==, !=, <, <=, >, >=) and show how to use them to compare values in conditionals.

Understand the Concept of Conditionals

What Are Conditionals?

Conditionals in programming are like decision-making tools for a computer. They allow the computer to make choices and take different actions based on specific conditions or criteria. Imagine it as a branching path in a story where the plot changes depending on the choices made.

Why Do We Use Conditionals?

We use conditionals to make our programs smart and responsive. Just like in real life, we often make decisions based on certain conditions. For example, if it’s raining, you might decide to take an umbrella with you. If it’s not raining, you might leave the umbrella at home. Similarly, conditionals help our programs make decisions and respond accordingly.

How Do Conditionals Work?

In programming, we use conditionals to check whether something is true or false. Think of it as asking a yes-or-no question. If the answer is “yes” (true), the program does one thing; if the answer is “no” (false), it does something else. Here’s a simple example in Java:

1
2
3
4
5
if (itIsRaining) {
    takeUmbrella();
} else {
    leaveUmbrellaAtHome();
}

In this code:

  • We have a condition: itIsRaining.
  • If itIsRaining is true, the program calls takeUmbrella().
  • If itIsRaining is false, the program calls leaveUmbrellaAtHome().

So, conditionals help our program adapt and make choices based on the situation, just like we do in everyday life.

Real-Life Analogy:

When the light is green, you go. When it’s red, you stop. Conditionals in programming work similarly by determining what the program should do based on specific conditions.

Introduction to Boolean Values

The Basics:

In programming, we often need to work with conditions that can be either true or false. Boolean values are like the “yes” and “no” answers in programming.

Real-Life Examples:

These real-life examples illustrate the concept of true and false:

  1. Light Switch:

True: When the light switch is in the “on” position, the light is on. False: When the light switch is in the “off” position, the light is off.

  1. Weather Conditions:

True: If it’s raining outside, you need an umbrella. False: If it’s not raining, you don’t need an umbrella.

  1. Traffic Light:

True: When the traffic light is green, it means you can go. False: When the traffic light is red, it means you must stop.

  1. Door Lock:

True: If the door is locked, you cannot enter without a key. False: If the door is unlocked, you can enter without a key.

  1. Alarm Clock:

True: When the alarm clock’s time matches the set alarm time, it rings to wake you up. False: When the alarm clock’s time doesn’t match the set alarm time, it remains silent.

  1. Weather Forecast:

True: If the weather forecast predicts rain, you might carry an umbrella. False: If the forecast predicts clear skies, you won’t need an umbrella.

  1. Binary Code:

True: In binary code (used in computers), “1” represents true or on, while “0” represents false or off.

  1. Password Authentication:

True: Entering the correct password grants access to a secure account. False: Entering an incorrect password denies access.

  1. Game State:

True: In a video game, if your character has low health points (HP), you may need to find health potions. False: If your character has full health, you don’t need to find health potions.

  1. Smartphone Screen:

True: When you touch the smartphone screen, it responds to your touch. False: When you don’t touch the screen, it remains inactive.

These real-life examples demonstrate situations where the concept of true (yes) and false (no) decisions is clear.

The boolean Data Type:

In Java, we use the boolean keyword to declare boolean variables.

1
2
boolean isSkyBlue = true;
boolean isLightOn = false;

Relate boolean Data Type to Conditions:

Boolean values are often used in conditions to make decisions. For example:

1
2
3
4
5
if (isSkyBlue) {
    // Do something when the sky is blue
} else {
    // Do something else when the sky is not blue
}

Logical Thinking:

Ask questions like:

  • If it’s sunny (true), should you bring sunglasses?
  • If it’s not sunny (false), do you still need sunglasses?

boolean values are about making choices based on conditions.

Boolean Operators:

  • && (logical AND): Returns true only if both conditions are true.
  • || (logical OR): Returns true if at least one condition is true.
  • ! (logical NOT): Flips the boolean value (true becomes false, and vice versa).
  • ^ (XOR or Exclusive OR): Returns true if condition A or B is true, but NOT both A and B.

Practice:

1
2
3
4
5
6
7
8
boolean isSunny = true;
boolean isWarm = true;

if (isSunny && isWarm) {
    // You might want to go to the beach
} else {
    // Consider other plans
}

Visual Aids:

  • Basic if else
graph LR A[Start] --> B[Evaluate Condition] B -->|Yes| C[Take an umbrella] B -->|No| D[No need for an umbrella] C --> E[End] D --> E
  • if, else if, else
graph LR A[Start] --> B[Evaluate Condition 1] B -->|Yes| C[Take an umbrella] B -->|No| D[Evaluate Condition 2] D -->|Yes| E[Take a light jacket] D -->|No| F[Leave the umbrella at home] E --> G[End] C --> G F --> G

Basic Statements in Java

If

  1. Syntax of the “if” statement
    • Includes the keyword if, followed by a condition enclosed in parentheses, and a block of code enclosed in curly braces.
      1
      2
      3
      if (condition) {
          // Code to execute if the condition is true
      }
      
  2. Boolean Expressions: The condition in an “if” statement must evaluate to a boolean expression, which can be either true or false.
    • The “if” statement executes the code block if the condition is true and skips it if the condition is false.
  3. Decision-Making: “if” statements are used for decision-making in programming.
    • They allow the program to take different actions based on whether a specific condition is met.
  4. Indentation: Proper code indentation within the “if” statement’s block improves code readability.
  5. Blocks of Code: Code to be executed when the condition is true should be enclosed within curly braces {}.
    • If there’s only a single statement to execute, the braces are optional, but it’s recommended to use them for clarity and maintainability.
  6. Execution Flow: The program’s flow of execution is affected by the “if” statement.
    • If the condition is true, the code inside the “if” block is executed, and then the program continues with the next statement after the “if” statement.
    • If the condition is false, the “if” block is skipped, and the program moves directly to the next statement.
      1
      2
      3
      4
      5
      int age = 18;
      
      if (age >= 18) {
          System.out.println("You are eligible to vote.");
      }
      
  7. Logical Operators: Logical operators can be used to create compound conditions in “if” statements.
1
2
3
4
5
int age = 25;

if (age >= 18 && age <= 30) {
    System.out.println("You are a young adult.");
}
1
2
3
4
5
6
String username = "user123";
String password = "securePass";

if (username.equals("user123") && password.equals("securePass")) {
    System.out.println("Login successful.");
}
1
2
3
4
5
6
boolean isSunny = true;
boolean isWeekend = false;

if (isSunny || isWeekend) {
    System.out.println("Let's go for a picnic!");
}
1
2
3
4
5
int grade = 75;

if (grade >= 60 && !(grade >= 90)) {
    System.out.println("You passed, but you didn't get an A.");
}
1
2
3
4
5
6
7
8
double totalAmount = 120.0;
boolean isMember = true;

if ((totalAmount >= 100.0 && totalAmount <= 200.0) || isMember) {
    System.out.println("You are eligible for a discount.");
} else {
    System.out.println("No discount available.");
}

If-Else

  1. Purpose of “if-else”: The “if-else” statement is used for decision-making in Java just like the basic if.
    • It allows the program to execute one block of code if a condition is true (the “if” part) and another block of code if the condition is false (the “else” part).
  2. Basic Syntax:
    • NOTE the use of curly braces {} to enclose the code blocks.
      1
      2
      3
      4
      5
      if (condition) {
          // Code to execute if the condition is true
      } else {
          // Code to execute if the condition is false
      }
      
  3. Conditions: Just like the basic if, the condition within the parentheses must be a boolean expression.
    • The code block under if is executed if the condition is true, and the code block under “else” is executed if the condition is false.
  4. Exclusive Execution: In an “if-else” statement, ONLY one of the code blocks (either the “if” block or the “else” block) will be executed, depending on the condition’s outcome.
  5. Indentation: Proper code indentation is STILL important for readability and maintainability.
    • The code inside the “if” and “else” blocks should be indented consistently.
  6. Examples:
    1
    2
    3
    4
    5
    6
    7
    8
    int score = 85;
    
    if (score >= 60) {
        System.out.println("You passed the exam.");
    } else {
        System.out.println("You failed the exam.");
    }
    i
    

If-Else If-Else

  1. These “else if” clauses allow for handling multiple conditions in a cascading manner.

  2. If-Else If are checked sequentially until ONLY one of them evaluates to true.

  3. Syntax:

    1
    2
    3
    4
    5
    6
    7
    if (condition1) {
        // Code for condition1 being true
    } else if (condition2) {
        // Code for condition2 being true
    } else {
        // Code if neither condition1 nor condition2 is true
    }
    

  4. Simple Example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    int num = 7;
    
    if (num > 10) {
        System.out.println("The number is greater than 10.");
    } else if (num < 10) {
        System.out.println("The number is less than 10.");
    } else {
        System.out.println("The number is equal to 10.");
    }
    
  5. Default “else” Block: The “else” block is optional.
    • If it’s not present, and the “if” condition is false, the program simply moves to the code following the “if-else” statement.
  6. Mutually Exclusive Conditions: The conditions in “if-else if-else” chains should be mutually exclusive.
    • MEANING only one condition should be true at a time.
  7. Advanced Examples
    • In this example, the “if-else” statements evaluate the score and assign a grade based on different score ranges.
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      int score = 85;
      char grade;
      
      if (score >= 90) {
          grade = 'A';
      } else if (score >= 80) {
          grade = 'B';
      } else if (score >= 70) {
          grade = 'C';
      } else if (score >= 60) {
          grade = 'D';
      } else {
          grade = 'F';
      }
      
      System.out.println("Your grade is: " + grade);
      
    • This example checks the lengths of the sides to determine if a triangle is equilateral, isosceles, or scalene.
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      int side1 = 3;
      int side2 = 4;
      int side3 = 5;
      String triangleType;
      
      if (side1 == side2 && side2 == side3) {
          triangleType = "Equilateral";
      } else if (side1 == side2 || side2 == side3 || side1 == side3) {
          triangleType = "Isosceles";
      } else {
          triangleType = "Scalene";
      }
      
      System.out.println("The triangle is: " + triangleType);
      
    • This example calculates the ticket price based on age and student status, with different price tiers.
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      int age = 25;
      boolean isStudent = false;
      double ticketPrice;
      
      if (age < 12) {
          ticketPrice = 5.0;
      } else if (age >= 12 && age <= 18) {
          ticketPrice = 10.0;
      } else if (isStudent && age <= 30) {
          ticketPrice = 15.0;
      } else {
          ticketPrice = 20.0;
      }
      
      System.out.println("Ticket price: $" + ticketPrice);
      
    • This example calculates a discount for an online shopping cart based on membership status and order subtotal.
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      double subtotal = 150.0;
      boolean isMember = true;
      boolean isPrimeMember = false;
      double discount = 0.0;
      
      if (isMember) {
          discount = subtotal * 0.1;
      } else if (isPrimeMember) {
          discount = subtotal * 0.15;
      } else if (subtotal >= 100.0) {
          discount = subtotal * 0.05;
      }
      
      double total = subtotal - discount;
      System.out.println("Total amount after discount: $" + total);
      
  8. Ordering Conditions: If you have “if-else if” conditions out of order, the program will still compile and run without errors. However, the order of the conditions matters because the program will execute the first “if” or “else if” block whose condition evaluates to true, and then it will skip the rest of the “else if” and “else” blocks.

    • Consider the following example and what would happen if x is 5.
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      int x = 5;
      
      if (x > 10) {
          System.out.println("x is greater than 10");
      } else if (x > 5) {
          System.out.println("x is greater than 5");
      } else if (x > 2) {
          System.out.println("x is greater than 2");
      } else {
          System.out.println("x is something else");
      }
      
    • To correct bypassing the x > 2 condition, you can correct the code like so:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      int x = 5;
      
      if (x > 10) {
          System.out.println("x is greater than 10");
      } else if (x > 2) {
          System.out.println("x is greater than 2");
      } else {
          System.out.println("x is something else");
      }
      

Nested Conditionals

  1. It’s possible to place one “if” statement inside another. This is called “nesting” or using nested “if” statements.
    • A real world example would be Russian nesting dolls (Matryoshka dolls) to help visualize the idea of one condition within another. matryoshka_dolls
  2. Visual of Nesting Conditions:
    • We start with the “Start” node.
    • We first check the season using the “Check Season” node.
    • Depending on the season (Spring, Summer, Fall, or Winter), we follow different paths to check the weather conditions using the “Check Weather” nodes.
    • Based on both the season and weather, we make clothing decisions, and the flowchart ultimately leads to the “End” node.
      graph TD A[Start] --> B[Check Season] B -->|Spring| C[Check Weather] B -->|Summer| D[Check Weather] B -->|Fall| E[Check Weather] B -->|Winter| F[Check Weather] C -->|Sunny| G[Wear a T-shirt and shorts] C -->|Rainy| H[Take an umbrella] D -->|Sunny| I[Wear sunglasses and shorts] D -->|Rainy| J[Wear a raincoat] E -->|Sunny| K[Wear a light jacket] E -->|Rainy| L[Take an umbrella] F -->|Sunny| M[Wear a heavy coat] F -->|Snowy| N[Wear a winter jacket] G -->O[End] H -->O I -->O J -->O K -->O L -->O M -->O N -->O
  3. Consider this simple example in java that has a single level of nesting and checks weather conditions on a day of the week:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    String dayOfWeek = "Saturday";
    String weather = "Sunny";
    
    if (dayOfWeek.equals("Saturday")) {
        if (weather.equals("Sunny")) {
            System.out.println("Let's go to the beach!");
        } else {
            System.out.println("It's not sunny, let's do something else.");
        }
    } else {
        System.out.println("It's not the weekend, so no beach today.");
    }
    
  4. Now let’s take a look at a more advanced example:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    import java.util.Scanner;
    
    public class TextAdventureGame {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String choice;
    
            System.out.println("Welcome to the Text Adventure Game!");
            System.out.println("You are in a dark forest. You come to a fork in the road.");
            System.out.print("Do you go left or right? (left/right): ");
            choice = scanner.nextLine();
    
            if (choice.equals("left")) {
                System.out.println("You encounter a friendly squirrel.");
                System.out.print("Do you want to befriend it? (yes/no): ");
                choice = scanner.nextLine();
    
                if (choice.equals("yes")) {
                    System.out.println("You and the squirrel become best friends!");
                } else {
                    System.out.println("You continue on your journey.");
                }
            } else {
                System.out.println("You find a treasure chest!");
                System.out.print("Do you open it? (yes/no): ");
                choice = scanner.nextLine();
    
                if (choice.equals("yes")) {
                    System.out.println("Congratulations! You found a valuable treasure!");
                } else {
                    System.out.println("You decide to leave the treasure and explore further.");
                }
            }
    
            System.out.println("Thanks for playing the Text Adventure Game!");
        }
    }
    
    • The program begins in a dark forest and presents the player with a choice to go left or right.
    • Depending on the choice, the program follows different branches of the decision tree.
    • If the player chooses to befriend the squirrel or open the treasure chest, it leads to different outcomes.
    • The nested conditionals determine the course of the game based on the player’s choices.
  5. Proper indention is even more important for readability and maintainability when dealing with nested conditions.
Nested Excercise

Problem: Vacation Planner

You are tasked with creating a vacation planner program. The program should ask the user a series of questions to help them plan their vacation. The questions and conditions are as follows:

  1. Ask the user if they want a relaxing vacation or an adventurous vacation.
    • If they choose “relaxing,” ask if they prefer a beach destination or a spa retreat.
      • If they choose “beach,” recommend a tropical beach destination.
      • If they choose “spa,” recommend a luxurious spa resort.
    • If they choose “adventurous,” ask if they prefer a mountain adventure or a city exploration.
      • If they choose “mountain,” recommend a hiking trip in the mountains.
      • If they choose “city,” recommend a cultural city tour.
  2. Ask the user if they want to go on a solo trip or with family/friends.
    • If they choose “solo,” recommend a solo-friendly destination based on their previous choice.
    • If they choose “with family/friends,” recommend a group-friendly destination based on their previous choice.
  3. Ask the user if they have a budget constraint (yes/no).
    • If they answer “yes,” ask for their budget in dollars.
      • Recommend a destination that fits their budget and preferences.
    • If they answer “no,” recommend a destination based on their preferences.

Ensure that the program guides the user through the decision-making process, taking into account their choices at each step. The program should provide a final recommendation for their vacation destination based on their preferences.

Challenge: Implement this vacation planner using nested if-else statements to handle the various combinations of choices and conditions. Make the program user-friendly and informative, providing clear recommendations at each step.

Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 import java.util.Scanner;

 public class VacationPlanner {
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);

         System.out.println("Welcome to the Vacation Planner!");
         System.out.print("Do you want a relaxing vacation or an adventurous vacation? (relaxing/adventurous): ");
         String vacationType = scanner.nextLine();

         if (vacationType.equals("relaxing")) {
             System.out.print("Do you prefer a beach destination or a spa retreat? (beach/spa): ");
             String relaxationChoice = scanner.nextLine();
             if (relaxationChoice.equals("beach")) {
                 System.out.println("We recommend a tropical beach destination for a relaxing vacation.");
             } else if (relaxationChoice.equals("spa")) {
                 System.out.println("We recommend a luxurious spa resort for a relaxing vacation.");
             } else {
                 System.out.println("Invalid choice.");
             }
         } else if (vacationType.equals("adventurous")) {
             System.out.print("Do you prefer a mountain adventure or a city exploration? (mountain/city): ");
             String adventureChoice = scanner.nextLine();
             if (adventureChoice.equals("mountain")) {
                 System.out.println("We recommend a hiking trip in the mountains for an adventurous vacation.");
             } else if (adventureChoice.equals("city")) {
                 System.out.println("We recommend a cultural city tour for an adventurous vacation.");
             } else {
                 System.out.println("Invalid choice.");
             }
         } else {
             System.out.println("Invalid choice.");
         }

         System.out.print("Do you want to go on a solo trip or with family/friends? (solo/with family or friends): ");
         String travelCompanions = scanner.nextLine();

         if (travelCompanions.equals("solo")) {
             System.out.println("We recommend a solo-friendly destination based on your previous choice.");
         } else if (travelCompanions.equals("with family or friends")) {
             System.out.println("We recommend a group-friendly destination based on your previous choice.");
         } else {
             System.out.println("Invalid choice.");
         }

         System.out.print("Do you have a budget constraint? (yes/no): ");
         String budgetConstraint = scanner.nextLine();

         if (budgetConstraint.equals("yes")) {
             System.out.print("Enter your budget in dollars: $");
             double budget = scanner.nextDouble();
             // You can implement budget-based recommendations here.
         }

         System.out.println("Enjoy planning your vacation!");
     }
 }

Java Switch Statements

  1. Switch statements are control structures in Java that allow you to execute different blocks of code based on the value of an expression. They provide an alternative to long chains of if-else if-else statements, making your code more concise and readable.
  2. Syntax:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    switch (expression) {
        case value1:
            // Code to execute when expression matches value1
            break;
        case value2:
            // Code to execute when expression matches value2
            break;
        // Additional cases...
        default:
            // Code to execute when none of the cases match the expression
    }
    
  3. Let’s see an example. We want to create a program that takes a number from 1 to 7 as input and prints the corresponding day of the week.
Switch Excercise
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Scanner;

public class DayOfWeek {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number from 1 to 7: ");
        int day = scanner.nextInt();

        switch (day) {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            case 4:
                System.out.println("Wednesday");
                break;
            case 5:
                System.out.println("Thursday");
                break;
            case 6:
                System.out.println("Friday");
                break;
            case 7:
                System.out.println("Saturday");
                break;
            default:
                System.out.println("Invalid input. Please enter a number from 1 to 7.");
        }
    }
}
  • Now a new Monkey-Wrench, the enhanced switch statement.
    • Starting from Java 12, you can use enhanced switch statements that simplify the code further. Here’s the same example using an enhanced switch statement:
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
       import java.util.Scanner;
      
       public class EnhancedDayOfWeek {
           public static void main(String[] args) {
               Scanner scanner = new Scanner(System.in);
               System.out.print("Enter a number from 1 to 7: ");
               int day = scanner.nextInt();
      
               String dayOfWeek = switch (day) {
                   case 1 -> "Sunday";
                   case 2 -> "Monday";
                   case 3 -> "Tuesday";
                   case 4 -> "Wednesday";
                   case 5 -> "Thursday";
                   case 6 -> "Friday";
                   case 7 -> "Saturday";
                   default -> "Invalid input. Please enter a number from 1 to 7.";
               };
      
               System.out.println(dayOfWeek);
           }
       }
      
    • Enhanced switch statements use the -> arrow syntax and allow you to directly assign the result to a variable. This makes the code more concise and readable, especially when dealing with multiple cases.