Methods & Overloading
Anatomy of a method
public static int add(int a, int b) {
return a + b;
}
modifiers returnType name(parameters) { body }
- Parameters are the variables in the definition (
a,b). - Arguments are the actual values you pass in:
add(2, 3). returnsends a value back and ends the method. Avoidmethod returns nothing.
static vs instance methods
staticmethods belong to the class:Math.max(3, 7).- Instance methods belong to an object:
"java".toUpperCase(). You'll build these in Unit 6.
Java is always pass-by-value
- For primitives, the method gets a copy. Changing it doesn't affect the caller.
- For objects, the method gets a copy of the reference. It can change the object's contents, but it can't make the caller's variable point to a new object.
Method overloading
Same name, different parameter list (number, types or order):
static int area(int side) { return side * side; }
static int area(int w, int h) { return w * h; }
static double area(double radius) { return Math.PI * radius * radius; }
Java picks the right one based on the arguments. ⚠️ Changing only the return type is not overloading and won't compile.
Good method habits
- One method = one job.
- Use verb names:
calculateTotal(),isValid(),sendEmail(). - Keep them short. If you scroll a lot, split it up.
Example
public class Shapes {
static int area(int side) { return side * side; }
static int area(int w, int h) { return w * h; }
static double area(double radius) { return Math.PI * radius * radius; }
public static void main(String[] args) {
System.out.println(area(4)); // 16
System.out.println(area(3, 5)); // 15
System.out.printf("%.2f%n", area(2.0)); // 12.57
}
}