SyntaxPilot
Courses/Java/Lesson 11

Java · Lesson 11 of 51 · 15 min

Methods, pass-by-value, overloading

queued

These are the notes for Java episode 11. You will learn why copy-pasted code is dangerous (we overcharge a customer live), what a method is, void methods and methods that return a value, parameters vs arguments, four errors every beginner meets, local variables and scope, the call stack, why Java is always pass-by-value (and what that means for arrays), and method overloading. Every example below runs as-is in the SyntaxPilot compiler, with its real output from javac 21.

The problem: a copy-paste bill bug

Raju's chai stall adds 5% GST (Goods and Services Tax, the tax added to a bill) to every bill: amount * 105 / 100. Three tables are waiting, so the obvious way is to write the bill lines once and copy-paste them. While editing the third copy, a finger slips: 105 becomes 150.

public class Main {
    public static void main(String[] args) {
        int t1 = 200;
        System.out.println("Table 1: Rs " + t1 * 105 / 100);
        System.out.println("------------");
        int t2 = 350;
        System.out.println("Table 2: Rs " + t2 * 105 / 100);
        System.out.println("------------");
        int t3 = 120;
        System.out.println("Table 3: Rs " + t3 * 150 / 100);
        System.out.println("------------");
    }
}
Table 1: Rs 210
------------
Table 2: Rs 367
------------
Table 3: Rs 180
------------

Table 3 pays Rs 180 for Rs 120 of chai. It should be Rs 126. No error, no warning: Java ran exactly what we typed.

Why: the same rule ("add 5%") lives in three places. One slip in one copy gives a wrong result, and when the GST rate changes you must find and edit every copy. We want to write the rule once, give it a name, and reuse it.

The fix: methods

Real-life example: mom's chai recipe card.

In a kitchen In Java
the recipe card, written once and kept in a box a method: a named block of steps
saying "make chai!" calling the method: line();
"for 4 people": what you hand over a parameter: an input the method needs
the cup of chai you get back the return value: the answer it hands back

A method is a named block of code that does one job. You write it once and call it (run it by its name) as many times as you like.

A void method: does a job, returns nothing

public class Main {
    static void line() {
        System.out.println("------------");
    }

    public static void main(String[] args) {
        System.out.println("Table 1");
        line();
        System.out.println("Table 2");
        line();
    }
}
Table 1
------------
Table 2
------------
  • The method is written inside the class but outside main.
  • static lets us call it straight from main without creating an object first (the full story comes in the classes episodes).
  • void means the method returns nothing; it just does a job.
  • line(); is a call: the method's name, round brackets, semicolon.
  • Change the dashes to stars in one place, and every call prints stars.

A method with a parameter and a return value

static int withGst(int amount) {
    return amount * 105 / 100;
}
Part Name Meaning
int (before the name) return type the type of the answer that comes back (void = no answer)
withGst method name a verb-like name saying what it does
int amount parameter an input slot: a type and a name, used like a variable inside
return ...; return statement hands the answer back to the caller and leaves the method
withGst(200) call with an argument 200 is the real value put into the slot

Parameter = the empty slot in the recipe. Argument = what you actually put in it.

public class Main {
    static int withGst(int amount) {
        int total = amount * 105 / 100;
        return total;
    }

    public static void main(String[] args) {
        System.out.println("Table 1: Rs " + withGst(200));
        System.out.println("Table 2: Rs " + withGst(350));
        System.out.println("Table 3: Rs " + withGst(120));
    }
}
Table 1: Rs 210
Table 2: Rs 367
Table 3: Rs 126

Each call jumps into the method with a different amount and comes back with the answer, right where the call was written. When the GST rate changes, we edit one line. (350 * 105 / 100 is 367 because int division drops the decimals, as in episode 3.)

Four method errors (real messages)

1. Promising a value and not returning it

static int withGst(int amount) {
    int total = amount * 105 / 100;
}
Main.java:4: error: missing return statement
    }
    ^

The return type int is a promise. Keep it with return total;, or make the method void.

2. Wrong argument type

System.out.println(withGst("200"));
Main.java:7: error: incompatible types: String cannot be converted to int
        System.out.println(withGst("200"));
                                   ^

3. Storing the "result" of a void method

int x = line();
Main.java:7: error: incompatible types: void cannot be converted to int
        int x = line();
                    ^

4. Wrong number of arguments

System.out.println(withGst());
Main.java:7: error: method withGst in class Main cannot be applied to given types;
        System.out.println(withGst());
                           ^
  required: int
  found:    no arguments
  reason: actual and formal argument lists differ in length

("Formal" arguments are the parameters; "actual" arguments are the values you pass.)

Local variables and scope

Real-life example: a hotel room. Your room's lamp only works in your room, and when you check out, the room is cleaned.

In a hotel In Java
your room a method's { }
the lamp, only usable in that room a local variable, like total inside withGst
check out: the room is cleaned the method returns: its local variables are gone

A local variable is a variable declared inside a method (parameters are local too). Its scope, the part of the code where it can be used, is that method only.

public class Main {
    static int withGst(int amount) {
        int total = amount * 105 / 100;
        return total;
    }

    public static void main(String[] args) {
        withGst(200);
        System.out.println(total);
    }
}
Main.java:9: error: cannot find symbol
        System.out.println(total);
                           ^
  symbol:   variable total
  location: class Main

Fix: store what comes back: int total = withGst(200);. The returned value is the only thing that leaves the method. (The two variables named total are different variables in different rooms.)

The call stack

Real-life example: a pile of plates at a wedding buffet. Each call puts a new plate on top; only the top plate is "running"; return takes the top plate off and the one below continues exactly where it stopped. This pile is the call stack: last in, first out. Each plate (a stack frame) holds that call's parameters and local variables.

public class Main {
    static int withGst(int amount) {
        System.out.println("  withGst starts");
        return amount * 105 / 100;
    }
    static void bill(int amount) {
        System.out.println(" bill starts");
        System.out.println(" Pay Rs " + withGst(amount));
        System.out.println(" bill ends");
    }

    public static void main(String[] args) {
        System.out.println("main starts");
        bill(200);
        System.out.println("main ends");
    }
}
main starts
 bill starts
  withGst starts
 Pay Rs 210
 bill ends
main ends
            withGst      <- top: running
  bill      bill         bill
  main      main         main        main
  ------    ------       ------      ------
  call      call         return      return
  bill      withGst      210         (bill ends)

Pass-by-value

Real-life example: a photocopy of your marksheet. You keep the original and hand the clerk a photocopy. The clerk can scribble on it; your original never changes.

At the office In Java
your original marksheet int marks in main
a photocopy for the clerk the parameter gets a copy of the value
your original is untouched main's marks is unchanged

Pass-by-value means a method always receives a copy of each argument's value.

public class Main {
    static void addBonus(int marks) {
        marks = marks + 10;
        System.out.println("Inside: " + marks);
    }

    public static void main(String[] args) {
        int marks = 70;
        addBonus(marks);
        System.out.println("Outside: " + marks);
    }
}
Inside: 80
Outside: 70

The fix: return the new value and store it.

public class Main {
    static int addBonus(int marks) {
        return marks + 10;
    }

    public static void main(String[] args) {
        int marks = 70;
        marks = addBonus(marks);
        System.out.println("Now: " + marks);
    }
}
Now: 80

Arrays: the copy is a copy of the address

From episode 7: an array variable holds a reference, the address of the array in memory. Passing an array copies that reference. Real-life example: giving a painter a slip with your address.

Your house In Java
your one real house the array object {70, 55}
a slip with the address (a copy) the parameter m: a copy of the reference
the painter paints your wall m[i] = m[i] + 10 changes the real array
the painter scribbles a new address on his slip m = new int[]{0, 0} changes only the copy
public class Main {
    static void addBonus(int[] m) {
        for (int i = 0; i < m.length; i++) {
            m[i] = m[i] + 10;
        }
    }
    static void replace(int[] m) {
        m = new int[]{0, 0};
    }

    public static void main(String[] args) {
        int[] marks = {70, 55};
        addBonus(marks);
        System.out.println(marks[0] + " " + marks[1]);
        replace(marks);
        System.out.println(marks[0] + " " + marks[1]);
    }
}
80 65
80 65

Interview line: Java is always pass-by-value. For objects and arrays, the value that is copied is the reference, so a method can change the object's contents, but it can never make the caller's variable point to a different object.

Method overloading

add(int a, int b) works for add(2, 3). But prices with paise?

public class Main {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2.5, 1.5));
    }
}
Main.java:8: error: incompatible types: possible lossy conversion from double to int
        System.out.println(add(2.5, 1.5));
                               ^

We could invent addInt, addDouble, addThree... Real-life example: a railway counter. You just say "book a ticket", sometimes handing over a name, sometimes a name and an age; the clerk looks at what you gave and does the right thing.

Method overloading = several methods with the same name but different parameter lists. Java picks the one whose parameters match the arguments.

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

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2.5, 1.5));
        System.out.println(add(1, 2, 3));
    }
}
5
4.0
6

You have used overloading since episode 1: System.out.println(5), println("chai"), println(2.5) and println('A') are different println methods with one name.

The method signature

A method's signature is its name + parameter types (in order): add(int,int), add(double,double), add(int,int,int). Overloads must differ in the number, types or order of parameters. The return type is not part of the signature, so this fails:

static int add(int a, int b) {
    return a + b;
}
static double add(int a, int b) {
    return a + b;
}
Main.java:5: error: method add(int,int) is already defined in class Main
    static double add(int a, int b) {
                  ^

Common mistakes (and the real error messages)

Mistake Real message Why Fix
copy-pasting a rule no error, a wrong result in one copy the rule lives in many places put it in a method
no return in an int method missing return statement the return type is a promise return value; or make it void
withGst("200") incompatible types: String cannot be converted to int argument type must match withGst(200)
int x = line(); for a void method incompatible types: void cannot be converted to int void returns nothing call line(); on its own
withGst() method withGst in class Main cannot be applied to given types; (required: int, found: no arguments) wrong number of arguments withGst(200)
using a method's local variable in main cannot find symbol / symbol: variable total local variables live only in their method int total = withGst(200);
expecting a changed int parameter to change the caller no error, the old value stays pass-by-value: a copy return and store the new value
add(2.5, 1.5) with only add(int, int) incompatible types: possible lossy conversion from double to int a double doesn't fit an int add an overload add(double, double)
two methods differing only in return type method add(int,int) is already defined in class Main return type is not in the signature change the parameters or the name
writing a method inside main illegal start of expression methods go inside the class, outside other methods move it out of main

Mini project: a report card

Each method does one small job; main just calls report.

public class Main {
    static double average(int[] marks) {
        int sum = 0;
        for (int m : marks) {
            sum += m;
        }
        return (double) sum / marks.length;
    }
    static char grade(double avg) {
        if (avg >= 75) return 'A';
        if (avg >= 50) return 'B';
        return 'C';
    }
    static void report(String name, int[] marks) {
        double avg = average(marks);
        System.out.println(name + ": " + avg + " " + grade(avg));
    }

    public static void main(String[] args) {
        report("Priya", new int[]{90, 80, 85});
        report("Aman", new int[]{60, 45, 54});
        report("Ravi", new int[]{40, 35, 48});
    }
}
Priya: 85.0 A
Aman: 53.0 B
Ravi: 41.0 C
  • (double) sum / marks.length casts first, so the division keeps decimals (episode 4).
  • A return inside an if leaves the method at once, so grade needs no else.
  • new int[]{...} creates an array right inside the call.

Extend it: add static int highest(int[] marks), and print the class topper.

Practice

  1. Write max(int a, int b) and an overload max(int a, int b, int c) that reuses the first one.
  2. Write isEven(int n) that returns a boolean.
  3. Write area(double r) for a circle and an overload area(double l, double w) for a rectangle.
  4. Write reverseArray(int[] a) that reverses the caller's array in place (returns nothing).
  5. Predict, then run: a method swap(int a, int b) that swaps its parameters. Does main's pair change?
Solutions and hints
  1. java static int max(int a, int b) { return a > b ? a : b; } static int max(int a, int b, int c) { return max(max(a, b), c); }
  2. java static boolean isEven(int n) { return n % 2 == 0; }
  3. java static double area(double r) { return Math.PI * r * r; } static double area(double l, double w) { return l * w; }
  4. java static void reverseArray(int[] a) { for (int i = 0, j = a.length - 1; i < j; i++, j--) { int t = a[i]; a[i] = a[j]; a[j] = t; } } It works because the method gets a copy of the reference and changes the real array.
  5. No. a and b are copies; swapping the copies doesn't touch main's variables. That's pass-by-value.

Quick quiz

What does this print?

static void change(int x, int[] a) {
    x = 99;
    a[0] = 99;
}
// in main:
int x = 1;
int[] a = {1};
change(x, a);
System.out.println(x + " " + a[0]);
  • A. 1 1
  • B. 99 99
  • C. 1 99
  • D. 99 1
Answer

C. 1 99. x received a copy of 1, so main's x stays 1. a received a copy of the array's reference, so a[0] = 99 changed the real array.

Interview questions

  1. What is a method, and why use one? A named, reusable block of code that does one job: no duplicated code, one place to fix, readable main.
  2. Parameter vs argument? The parameter is the variable in the method's declaration; the argument is the actual value passed in the call.
  3. Is Java pass-by-value or pass-by-reference? Always pass-by-value. For objects/arrays the copied value is the reference, so contents can change but the caller's variable can't be re-pointed.
  4. What is method overloading? Same method name, different parameter lists (number, type or order), resolved at compile time.
  5. Can you overload by return type alone? No: the return type isn't part of the signature (method ... is already defined).
  6. What is a method signature? The method name plus its parameter types, in order.
  7. What is the call stack? The stack of active method calls; each call pushes a frame with its parameters and local variables, and return pops it (last in, first out).
  8. Where do local variables live, and how long? In the method's stack frame, only while that call runs.
  9. Can a void method use return? Yes, a bare return; to leave early.

Glossary

Term Meaning Example
method a named block of code that does one job static void line()
call (invoke) running a method by its name line();
void the method returns nothing static void line()
return type the type of the value a method gives back int in static int withGst(...)
return hands a value back to the caller and leaves the method return total;
return value the answer a method hands back 210 from withGst(200)
parameter an input slot in the method's declaration int amount
argument the actual value passed in a call 200 in withGst(200)
static belongs to the class; can be called from main without an object static int add(...)
local variable a variable declared inside a method (incl. parameters) total in withGst
scope the part of the code where a variable can be used total: only inside withGst
call stack the pile of active method calls, last in first out main → bill → withGst
stack frame one call's "plate": its parameters and local variables withGst's frame holds amount
pass-by-value a method receives a copy of each argument's value addBonus(marks)
reference the address of an object or array in memory the value in int[] marks
method overloading same name, different parameter lists add(int,int), add(double,double)
method signature the method name + parameter types add(int,int)
GST Goods and Services Tax, added to a bill amount * 105 / 100 for 5%
lossy conversion a conversion that could lose information double → int drops .5

Summary

  • Copy-pasted code copies mistakes; a method is written once and called by name.
  • void methods do a job; methods with a return type hand back an answer with return.
  • Parameters are the slots, arguments the values; they must match in number and type.
  • Local variables live only inside their method (scope); calls pile up on the call stack.
  • Java is always pass-by-value: an int parameter is a copy; an array parameter is a copy of the reference, so the method can change the real array's items.
  • Overloading: one name, different parameter lists; the signature is name + parameter types, and the return type alone can't tell overloads apart.

Next episode: Recursion: what happens when a method calls itself, and how to crash the call stack on purpose.