Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

3.5 Methods — which overload runs

Lesson

Java chooses by the arguments

When you call an overloaded method, Java looks at the number and types of the arguments you passed and runs the version whose parameter list matches. That is why the overloads must differ in their parameters — it is how Java tells them apart.


Worked example

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

System.out.println(add(2, 3));      // 5   (two-argument version)
System.out.println(add(2, 3, 4));   // 9   (three-argument version)

▶ Try it: both add overloads are defined for you. Run this — the number of arguments decides which one runs. Change the calls and re-run.



add(int, int) returns a + b; add(int, int, int) returns a + b + c. What does add(2, 3, 4) return?


How does Java decide which overloaded method to run?


add(int, int) returns a + b. Type what add(10, 5) returns:


True or false?