Learn Java · lesson 24 of 61 · about 9 minutes
Overloading and Scope
Split the bill between the group with a second money method of the same name, and see which variables a method can use.
What you'll learn
- Overload a method by parameter types
- Know that parameters are copies
- Explain local scope
Splitting the bill
Groups like to split the bill: Split 7 ways: $12.77 each. That's still money, so it can share the name: a second method money(int cents, int people) with two parameters. Java picks the version whose parameters match the call. And it can't just use bill and tickets from main: a method only sees its own parameters and variables, so main passes them in.
Overloading
Several methods can share a name if their parameter lists differ. Java picks the one that matches the arguments. That's why System.out.println works with ints, doubles and Strings.
One name, three versions
public class Main {
static String describe(int n) { return "int " + n; }
static String describe(double d) { return "double " + d; }
static String describe(String s) { return "text " + s; }
public static void main(String[] args) {
System.out.println(describe(3));
System.out.println(describe(2.5));
System.out.println(describe("hi"));
}
}Output
int 3
double 2.5
text hiScope and copies
Variables declared inside a method (or inside any braces) exist only there. Parameters receive copies of int, double and other basic values, so changing a parameter doesn't change the caller's variable.
Changing a copy
public class Main {
static void addBonus(int score) {
score += 10;
System.out.println("inside: " + score);
}
public static void main(String[] args) {
int score = 5;
addBonus(score);
System.out.println("outside: " + score);
}
}Output
inside: 15
outside: 5Both money methods
public class Main {
public static void main(String[] args) {
System.out.println(money(8945));
System.out.println(money(8945, 7));
}
// an amount in cents, shown as dollars
static String money(int cents) {
return String.format("$%d.%02d", cents / 100, cents % 100);
}
// an amount shared between people, shown as dollars each
static String money(int cents, int people) {
return money(cents / people) + " each";
}
}Output
$89.45
$12.77 eachNow try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.