Jan 24, 2026
## Chapter 8: Methods (Your Mini-Workers)
In the beginning, students write all their code inside `main`. It looks like a never-ending train. If there’s a bug, you’re lost.
I tell my students: **"A good `main` method should read like a set of steps, not a whole novel."** A method is just a worker you call to do one specific job.
### 1. Handing Back Results: The `return` Keyword
If you want a worker to calculate something and give you the answer, use `return`.
**Example 1: The Calculator Worker (Basic Example)**
```java
public static int add(int a, int b) {
return a + b;
}
```
**Example 2: The Ghost Code (Common Mistake)**
```java
public static int check() {
return 10;
System.out.println("I will never run!"); // ERROR: Unreachable code
}
```
*Teacher's Note:* Once `return` is executed, the method stops immediately. Anything after it is "Ghost Code"—it will never see the light of day.
### 2. The Xerox Analogy (Pass-by-Value)
This is the biggest confusion for students. When you pass a variable to a method, Java doesn't give the "original." It makes a **copy** (like a Xerox).
**Example 3: The Safe Variable (Explanation Focused)**
```java
public static void change(int x) {
x = 100; // Changes the copy
}
public static void main(String[] args) {
int myNum = 5;
change(myNum);
System.out.println(myNum); // Still 5! The original is safe.
}
```
### 3. The "Map" Exception (Arrays/Objects)
**Example 4: The Red Door (Real-Life Analogy)**
For arrays, Java copies the **address** (like a map). If two people have a copy of the same map, they both go to the same house.
```java
public static void paint(int[] arr) {
arr[0] = 99;
}
// If you pass an array here, the original WILL change!
```
**Example 5: Overloading (Future Hint)**
```java
void play() { ... }
void play(String song) { ... }
```
*Teacher's Note:* You can have two workers with the same name if they take different tools. This is called **Method Overloading**. We'll use this a lot in OOP.