Learning Objectives

Decision Making

Understand and use if, if-else, and switch statements

Loop Structures

Implement for, while, and do-while loops effectively

Loop Control

Use break and continue statements for loop control

Nested Structures

Apply nested control structures in complex scenarios

Expressions and Operators

Understanding Expressions

An expression is a combination of variables, operators, and method calls that evaluates to a single value. Expressions are the building blocks of Java control structures and are used in conditions, assignments, and calculations.

Arithmetic Operators

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 6 * 7 42
/ Division 15 / 3 5
% Modulus (remainder) 17 % 5 2

Arithmetic Examples

int a = 10, b = 3;
int sum = a + b;        // 13
int difference = a - b; // 7
int product = a * b;     // 30
int quotient = a / b;    // 3
int remainder = a % b;   // 1

// Integer division vs floating-point division
int intResult = 10 / 3;     // 3 (integer division)
double doubleResult = 10.0 / 3; // 3.333... (floating-point division)

Relational Operators

Operator Description Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 10 > 5 true
< Less than 3 < 7 true
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 4 <= 6 true

Relational Examples

int age = 18;
boolean isAdult = age >= 18;        // true
boolean isTeenager = age >= 13 && age <= 19; // true

String name1 = "Alice";
String name2 = "Alice";
boolean sameName = name1.equals(name2); // true (use equals() for strings)

// Comparing different data types
int number = 5;
double decimal = 5.0;
boolean equal = number == decimal; // true (automatic type conversion)

Logical Operators

Operator Description Example Result
&& Logical AND true && true true
|| Logical OR true || false true
! Logical NOT !true false
& Bitwise AND 5 & 3 1
| Bitwise OR 5 | 3 7
^ Bitwise XOR 5 ^ 3 6

Logical Examples

int age = 25;
boolean hasLicense = true;
boolean hasCar = false;

// Logical AND - both conditions must be true
boolean canDrive = age >= 18 && hasLicense; // true

// Logical OR - at least one condition must be true
boolean hasTransport = hasLicense || hasCar; // true

// Logical NOT - inverts the boolean value
boolean cannotDrive = !canDrive; // false

// Complex logical expressions
boolean isEligible = age >= 18 && hasLicense && !hasCar; // true

// Short-circuit evaluation
boolean result = false && someExpensiveMethod(); // someExpensiveMethod() is never called

Assignment Operators

Operator Description Example Equivalent To
= Simple assignment x = 5 x = 5
+= Add and assign x += 3 x = x + 3
-= Subtract and assign x -= 2 x = x - 2
*= Multiply and assign x *= 4 x = x * 4
/= Divide and assign x /= 2 x = x / 2
%= Modulus and assign x %= 3 x = x % 3

Assignment Examples

int counter = 0;

// Increment counter
counter += 1;  // counter = 1
counter += 5;  // counter = 6

// Decrement counter
counter -= 2;  // counter = 4

// Multiply counter
counter *= 3;  // counter = 12

// Divide counter
counter /= 2;  // counter = 6

// Modulus assignment
counter %= 4;  // counter = 2

// Multiple assignments in one line
int a = 5, b = 10, c = 15;

Increment and Decrement Operators

Operator Description Example Result
++ Increment by 1 ++x or x++ x + 1
-- Decrement by 1 --x or x-- x - 1

Pre-increment vs Post-increment

int x = 5;

// Pre-increment (++x) - increment first, then use
int result1 = ++x;  // x becomes 6, result1 = 6
System.out.println("x: " + x + ", result1: " + result1);

// Post-increment (x++) - use first, then increment
int y = 5;
int result2 = y++;  // result2 = 5, y becomes 6
System.out.println("y: " + y + ", result2: " + result2);

// Practical example in loops
for (int i = 0; i < 5; i++) {
    System.out.println("Count: " + i);
}

// Common mistake
int a = 5;
int b = a++ + ++a;  // b = 5 + 7 = 12 (a becomes 7)

Operator Precedence

Operator precedence determines the order in which operators are evaluated in an expression. Understanding precedence is crucial for writing correct expressions.

Precedence Operators Associativity
1 (Highest) () [] . Left to Right
2 ++ -- ! ~ Right to Left
3 * / % Left to Right
4 + - Left to Right
5 << >> >>> Left to Right
6 < <= > >= Left to Right
7 == != Left to Right
8 & Left to Right
9 ^ Left to Right
10 | Left to Right
11 && Left to Right
12 || Left to Right
13 ?: (ternary) Right to Left
14 (Lowest) = += -= *= /= %= Right to Left

Precedence Examples

// Without parentheses - follows precedence
int result1 = 2 + 3 * 4;  // 2 + 12 = 14 (multiplication first)

// With parentheses - explicit order
int result2 = (2 + 3) * 4;  // 5 * 4 = 20

// Complex expression
int a = 5, b = 3, c = 2;
int result3 = a + b * c / 2;  // 5 + 3 * 2 / 2 = 5 + 6 / 2 = 5 + 3 = 8

// Logical operators precedence
boolean result4 = true || false && true;  // true || false = true (&& has higher precedence)

// Use parentheses for clarity
boolean result5 = (true || false) && true;  // true && true = true

Ternary Operator

Ternary Operator Syntax

// Syntax: condition ? value_if_true : value_if_false
int age = 18;
String status = age >= 18 ? "Adult" : "Minor";
System.out.println(status); // "Adult"

// Nested ternary operator
int score = 85;
String grade = score >= 90 ? "A" : 
               score >= 80 ? "B" : 
               score >= 70 ? "C" : 
               score >= 60 ? "D" : "F";

// Ternary vs if-else
int max = (a > b) ? a : b;  // Same as:
if (a > b) {
    max = a;
} else {
    max = b;
}

Decision Making

Overview

Decision-making statements allow your program to execute different code blocks based on certain conditions. Java provides several ways to implement decision logic.

If Statement

Basic If Statement

if (condition) {
    // Code to execute if condition is true
}
Example
int age = 18;
if (age >= 18) {
    System.out.println("You are an adult.");
}

If-Else Statement

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}
Example
int score = 75;
if (score >= 60) {
    System.out.println("You passed the exam!");
} else {
    System.out.println("You failed the exam.");
}

If-Else-If Statement

if (condition1) {
    // Code for condition1
} else if (condition2) {
    // Code for condition2
} else if (condition3) {
    // Code for condition3
} else {
    // Default code if no conditions are met
}
Example
int grade = 85;
if (grade >= 90) {
    System.out.println("Grade: A");
} else if (grade >= 80) {
    System.out.println("Grade: B");
} else if (grade >= 70) {
    System.out.println("Grade: C");
} else if (grade >= 60) {
    System.out.println("Grade: D");
} else {
    System.out.println("Grade: F");
}

Nested If Statements

int age = 25;
boolean hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        System.out.println("You can drive legally.");
    } else {
        System.out.println("You need to get a license first.");
    }
} else {
    System.out.println("You are too young to drive.");
}

Switch Statement

Traditional Switch Statement

switch (expression) {
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    case value3:
        // Code for value3
        break;
    default:
        // Default code
        break;
}

Example

int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
    case 7:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Invalid day");
        break;
}

Switch Expressions (Java 14+)

// Switch expression with arrow syntax
String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    case 6, 7 -> "Weekend";
    default -> "Invalid day";
};

// Switch expression with yield
String dayName2 = switch (day) {
    case 1: yield "Monday";
    case 2: yield "Tuesday";
    case 3: yield "Wednesday";
    case 4: yield "Thursday";
    case 5: yield "Friday";
    case 6, 7: yield "Weekend";
    default: yield "Invalid day";
};

Switch with Strings (Java 7+)

String color = "red";
switch (color.toLowerCase()) {
    case "red":
        System.out.println("Stop!");
        break;
    case "yellow":
        System.out.println("Caution!");
        break;
    case "green":
        System.out.println("Go!");
        break;
    default:
        System.out.println("Unknown color");
        break;
}

Loops

For Loop

Traditional For Loop

for (initialization; condition; increment/decrement) {
    // Code to repeat
}
Examples
// Count from 1 to 10
for (int i = 1; i <= 10; i++) {
    System.out.println("Count: " + i);
}

// Count backwards
for (int i = 10; i >= 1; i--) {
    System.out.println("Countdown: " + i);
}

// Step by 2
for (int i = 0; i <= 20; i += 2) {
    System.out.println("Even number: " + i);
}

Enhanced For Loop (For-Each)

// For arrays
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println("Number: " + number);
}

// For collections
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
    System.out.println("Hello, " + name);
}

While Loop

while (condition) {
    // Code to repeat
    // Must modify condition to avoid infinite loop
}

Examples

int count = 1;
while (count <= 5) {
    System.out.println("Count: " + count);
    count++;
}

// Input validation
Scanner scanner = new Scanner(System.in);
int number;
do {
    System.out.print("Enter a positive number: ");
    number = scanner.nextInt();
} while (number <= 0);

Do-While Loop

do {
    // Code to repeat
} while (condition);

Example

int number;
Scanner scanner = new Scanner(System.in);

do {
    System.out.print("Enter a number between 1 and 10: ");
    number = scanner.nextInt();
} while (number < 1 || number > 10);

System.out.println("Valid number entered: " + number);

Loop Control Statements

Break Statement

The break statement terminates the current loop or switch statement.

// Break in for loop
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;  // Exit loop when i equals 5
    }
    System.out.println("Number: " + i);
}
System.out.println("Loop ended");

// Break in switch
switch (grade) {
    case 'A':
        System.out.println("Excellent!");
        break;
    case 'B':
        System.out.println("Good!");
        break;
    default:
        System.out.println("Keep trying!");
        break;
}

Continue Statement

The continue statement skips the current iteration and continues with the next iteration.

// Skip even numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    System.out.println("Odd number: " + i);
}

// Skip negative numbers
int[] numbers = {1, -2, 3, -4, 5};
for (int num : numbers) {
    if (num < 0) {
        continue;  // Skip negative numbers
    }
    System.out.println("Positive number: " + num);
}

Practical Examples

Number Guessing Game

import java.util.Scanner;
import java.util.Random;

public class NumberGuessingGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        
        int secretNumber = random.nextInt(100) + 1;  // 1 to 100
        int attempts = 0;
        boolean guessed = false;
        
        System.out.println("Welcome to the Number Guessing Game!");
        System.out.println("I'm thinking of a number between 1 and 100.");
        
        while (!guessed && attempts < 10) {
            System.out.print("Enter your guess: ");
            int guess = scanner.nextInt();
            attempts++;
            
            if (guess < secretNumber) {
                System.out.println("Too low! Try again.");
            } else if (guess > secretNumber) {
                System.out.println("Too high! Try again.");
            } else {
                guessed = true;
                System.out.println("Congratulations! You guessed it in " + attempts + " attempts!");
            }
            
            if (!guessed && attempts < 10) {
                System.out.println("Attempts remaining: " + (10 - attempts));
            }
        }
        
        if (!guessed) {
            System.out.println("Game over! The number was " + secretNumber);
        }
        
        scanner.close();
    }
}

Menu-Driven Calculator

import java.util.Scanner;

public class MenuCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean running = true;
        
        while (running) {
            System.out.println("\nSimple Calculator");
            System.out.println("================");
            System.out.println("1. Addition");
            System.out.println("2. Subtraction");
            System.out.println("3. Multiplication");
            System.out.println("4. Division");
            System.out.println("5. Exit");
            System.out.print("Enter your choice (1-5): ");
            
            int choice = scanner.nextInt();
            
            if (choice == 5) {
                running = false;
                System.out.println("Goodbye!");
                continue;
            }
            
            if (choice < 1 || choice > 4) {
                System.out.println("Invalid choice! Please enter 1-5.");
                continue;
            }
            
            System.out.print("Enter first number: ");
            double num1 = scanner.nextDouble();
            System.out.print("Enter second number: ");
            double num2 = scanner.nextDouble();
            
            double result = 0;
            String operation = "";
            
            switch (choice) {
                case 1:
                    result = num1 + num2;
                    operation = "+";
                    break;
                case 2:
                    result = num1 - num2;
                    operation = "-";
                    break;
                case 3:
                    result = num1 * num2;
                    operation = "*";
                    break;
                case 4:
                    if (num2 == 0) {
                        System.out.println("Error: Division by zero!");
                        continue;
                    }
                    result = num1 / num2;
                    operation = "/";
                    break;
            }
            
            System.out.printf("%.2f %s %.2f = %.2f%n", num1, operation, num2, result);
        }
        
        scanner.close();
    }
}

Summary

In this module, you've learned:

  • ? Decision-making statements (if, if-else, switch)
  • ? Expressions and operators (arithmetic, relational, logical)
  • ? Loop structures (for, while, do-while)
  • ? Loop control statements (break, continue)
  • ? Nested control structures
  • ? Switch expressions (Java 14+)
  • ? Operator precedence and ternary operator
  • ? Practical applications of control structures

Next Steps

  1. Complete the exercises in the exercises.md file
  2. Practice writing programs with various control structures
  3. Move to Module 4: Object-Oriented Programming Basics

?? Module 3 Complete!

You now have a solid understanding of Java control structures. Time to learn about object-oriented programming!