Java · Module 5 · Lesson 11 min read

Methods & Overloading

Anatomy of a method

Java
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).
  • return sends a value back and ends the method. A void method returns nothing.

static vs instance methods

  • static methods 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):

Java
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

Java
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
    }
}