Module 2: Building Blocks of Logic
Making decisions and repeating actions with Control Flow and Methods.
Giving Your Program a Brain
Welcome to Module 2! In the last module, you learned how to store data. Now, you'll learn how to make your program *do things* with that data. **Control Flow** is the order in which your program executes instructions. We'll learn how to make your code take different paths based on certain conditions (decision-making) and how to repeat tasks (loops). Finally, we'll introduce **methods** to organize our logic into clean, reusable blocks.
1Making Decisions with `if-else` Statements
Programs are rarely linear; they need to react differently to different inputs. This is achieved with conditional statements.
Comparison and Logical Operators
To make decisions, we first need to compare values. Java provides several operators for this:
- `==` (Equal to)
- `!=` (Not equal to)
- `>` (Greater than), `<` (Less than)
- `>=` (Greater than or equal to), `<=` (Less than or equal to)
We can also combine conditions with **logical operators**:
- `&&` (AND - both conditions must be true)
- `||` (OR - at least one condition must be true)
- `!` (NOT - inverts the boolean value)
The `if-else` Structure
The `if` statement executes a block of code only if a specified condition is true. You can add an `else if` for more conditions and an `else` block that runs if no previous conditions were met.
int userAge = 19;
boolean hasLicense = true;
if (userAge >= 18 && hasLicense) {
System.out.println("You are allowed to drive.");
} else if (userAge < 18) {
System.out.println("You are too young to drive.");
} else {
System.out.println("You must have a license to drive.");
}
2Repeating Actions with Loops
Loops allow you to execute a block of code multiple times, which is essential for working with collections of data or performing repetitive tasks.
The `for` Loop
The `for` loop is ideal when you know exactly how many times you want to repeat an action. It consists of three parts: initialization, condition, and increment.
// This loop will print numbers 1 through 5
for (int i = 1; i <= 5; i++) {
System.out.println("Current number: " + i);
}
Breakdown:
- `int i = 1;`: A counter variable `i` is initialized to 1. This happens only once.
- `i <= 5;`: The loop continues as long as this condition is true.
- `i++`: After each iteration, the counter `i` is incremented by 1.
The `while` Loop
The `while` loop is used when you want to repeat a block of code as long as a condition remains true. You don't necessarily know how many iterations it will take.
int countdown = 3;
while (countdown > 0) {
System.out.println(countdown);
countdown--; // Decrement the counter
}
System.out.println("Blast off!");
3Organizing Code with Methods
As your programs grow, you'll find yourself writing the same logic over and over. A **method** (often called a function in other languages) is a named block of code that performs a specific task. You can "call" the method whenever you need to perform that task, promoting code reuse and organization.
Defining and Calling a Method
Let's create a simple method that greets a user. It takes a piece of data (the user's name) as an input, called a **parameter**.
public class Main {
// The main method where the program starts
public static void main(String[] args) {
// Calling our new method
greetUser("Alice");
greetUser("Bob");
}
// Our custom method definition
public static void greetUser(String name) {
System.out.println("Hello, " + name + "! Welcome.");
}
}
Methods that Return Values
Methods can also perform a calculation and send a result back. Instead of `void` (which means "returns nothing"), you specify the data type of the value it will return.
public class Main {
public static void main(String[] args) {
int sum = addNumbers(5, 7); // Call the method and store the result
System.out.println("The sum is: " + sum); // Prints "The sum is: 12"
}
// This method returns an int
public static int addNumbers(int num1, int num2) {
int result = num1 + num2;
return result; // Send the result back
}
}