Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 6 of 20 · 6 min read

Java methods: parameters, return values and overloading

Java methods notes with examples: defining and calling methods, parameters and arguments, return values, pass by value, method overloading, scope and recursion.

What is a method?

A method is a named block of code that does one job. You write it once and call it whenever you need it. main is a method; System.out.println and Math.sqrt are methods written by others.

Methods make programs shorter (no copy-paste), easier to read (each name says what it does) and easier to fix (change one place).

Defining and calling a method

public class Greeter {
    static void greet() {
        System.out.println("Welcome to BrainBit Infotech!");
    }

    public static void main(String[] args) {
        greet();
        greet();
    }
}

The parts of a method header:

static  void   greet  ()
  |      |       |     |
  |      |       |     parameters (none here)
  |      |       name
  |      return type (void = returns nothing)
  modifier (static = belongs to the class; needed to call it from main directly)

Parameters and arguments

Parameters are the variables in the method header. Arguments are the values you pass in the call.

static void printTable(int n) {          // n is a parameter
    for (int i = 1; i <= 10; i++) {
        System.out.println(n + " x " + i + " = " + n * i);
    }
}

printTable(9);                            // 9 is an argument

Several parameters are separated by commas, each with its own type:

static void introduce(String name, int age) {
    System.out.println(name + " is " + age);
}

introduce("Meena", 15);

The arguments must match the parameters in number, type and order.

Return values

A method can send a value back with return. Its header names the type it returns:

static double area(double length, double width) {
    return length * width;
}

double a = area(12.5, 8);       // 100.0
System.out.println(area(3, 4)); // 12.0

return ends the method immediately. A method that returns a value must return on every path:

static String grade(int marks) {
    if (marks >= 40) {
        return "Pass";
    }
    return "Fail";
}

A boolean method reads well inside conditions:

static boolean isEven(int n) {
    return n % 2 == 0;
}

if (isEven(42)) System.out.println("Even");

Pass by value

Java always passes a copy of the argument's value. Changing a primitive parameter does not change the caller's variable:

static void addBonus(int marks) {
    marks += 5;               // changes the copy only
}

int m = 70;
addBonus(m);
System.out.println(m);        // still 70

To get a new value back, return it: m = withBonus(m);.

For objects and arrays the copy is a copy of the reference, so a method can change the contents of an array it receives (see the Arrays topic), but it cannot make the caller's variable point to a different array.

Method overloading

Several methods may share a name if their parameter lists differ (number or types):

static int add(int a, int b)          { return a + b; }
static int add(int a, int b, int c)   { return a + b + c; }
static double add(double a, double b) { return a + b; }

add(2, 3);        // calls the first: 5
add(2, 3, 4);     // the second: 9
add(2.5, 1.5);    // the third: 4.0

The compiler picks the version from the arguments. A different return type alone is not enough to overload.

Scope: where a variable lives

  • A variable declared inside a method (a local variable) exists only in that method.
  • A variable declared inside a block { } exists only in that block.
  • Two methods can each have a local variable called i without any clash.

Recursion

A recursive method calls itself. It needs a base case that stops the calls:

static long factorial(int n) {
    if (n <= 1) return 1;              // base case
    return n * factorial(n - 1);       // recursive case
}

factorial(5);   // 5 * 4 * 3 * 2 * 1 = 120

Without a base case the calls never end, and Java throws StackOverflowError.

Example: a GST calculator

public class Gst {
    static double withGst(double price, double ratePercent) {
        return price + price * ratePercent / 100;
    }

    static void printLine(String item, double price, double rate) {
        System.out.printf("%-10s %8.2f%n", item, withGst(price, rate));
    }

    public static void main(String[] args) {
        printLine("Shoes", 1200, 12);
        printLine("Phone", 15000, 18);
    }
}
Shoes       1344.00
Phone      17700.00

varargs: any number of arguments

static int total(int... nums) {
    int sum = 0;
    for (int n : nums) sum += n;
    return sum;
}

total(4, 5);          // 9
total(1, 2, 3, 4);    // 10

Inside the method, nums is an array. A varargs parameter must come last.

Common mistakes

  • Defining a method inside main or inside another method. Methods sit side by side inside the class.
  • Calling a non-static method from static main without an object: "non-static method cannot be referenced from a static context".
  • Forgetting return on one path: "missing return statement".
  • Ignoring the returned value: area(3, 4); on its own computes the area and throws it away.
  • Expecting a method to change an int passed to it.

Key points

  • A method has a return type, a name and a parameter list; void means it returns nothing.
  • Arguments must match parameters in number, type and order.
  • return sends back a value and ends the method.
  • Java passes copies of values; for objects that copy is a reference.
  • Overloading means same name, different parameter lists.
  • Recursion needs a base case.

Practice questions

1. Write a method max3(int a, int b, int c) that returns the largest of three numbers.
static int max3(int a, int b, int c) {
    return Math.max(a, Math.max(b, c));
}
2. Are these valid overloads? int sum(int a, int b) and double sum(int a, int b).

No. They differ only in return type; the parameter lists are the same, so the compiler reports a duplicate method.

3. What is printed?
static void change(int x) { x = 100; }
// in main:
int x = 5;
change(x);
System.out.println(x);

5. The method changes its own copy.

4. Write a method isPrime(int n) that returns true when n is prime.
static boolean isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}
5. Write a recursive method that returns the sum of the digits of a number.
static int digitSum(int n) {
    if (n == 0) return 0;
    return n % 10 + digitSum(n / 10);
}