Method Calls, Return Values, Arguments, and Overloading
What happens when a method is called: how control jumps and returns, how arguments become parameters, the difference between void and non-void methods, and how Java chooses among overloaded methods.
Calling a method is how a program uses code that lives somewhere else. A call interrupts the normal top-to-bottom flow: the program runs the method's statements, then continues right after the call. Calls pass arguments, which are copied into the method's parameters (call by value). A void method performs a task and returns nothing, so it is called as a statement on its own. A non-void method returns a value of its return type, which the caller must store or use. Several methods can share a name if their signatures differ; such methods are overloaded.
1Calling a Method
A method call names the method and supplies arguments in parentheses: printBanner(), square(6), pay(7.5, 20). An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature.
Arguments can be literals, variables, or any expressions; Java evaluates each argument to a value before the method begins. In square(a + 1), the expression a + 1 is computed first, and its value is what the method receives. Compatibility follows the usual type rules: an int argument can be passed to a double parameter through automatic widening, but a double argument cannot be passed to an int parameter.
| Term | Meaning | Example |
|---|---|---|
| Argument | A value passed into a method when it is called | 7.5 in pay(7.5, 20) |
| Parameter | A variable in the method header that receives the argument | double hours |
| Call by value | Parameters are initialized with copies of the arguments | Changing n does not change score |
| Return value | The value a non-void method gives back | square(6) returns 36 |
| void method | A method with no return value | printBanner() |
| Overloading | Several methods with the same name but different signatures | area(int), area(int, int) |
2Flow of Control
A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed, or a return statement is executed, the flow of control returns to the point immediately following where the method was called.
Calls can be nested: a method can call another method, which can call another. Each call pauses its caller, and the program keeps track of where to resume. When tracing, follow the calls rather than reading the file from top to bottom: jump into each method when it is called, run it to completion, and return exactly to where you left off.
| Step | Executing | Output so far |
|---|---|---|
| 1 | main: println("A") | A |
| 2 | main: greet() called | A |
| 3 | greet: println("B"), println("C") | A B C |
| 4 | greet ends; return to main | A B C |
| 5 | main: println("D") | A B C D |
Tracing Calls Inside Calls
Predict the exact output order.
public static void inner()
{
System.out.println(" inner");
}
public static void outer()
{
System.out.println(" outer start");
inner();
System.out.println(" outer end");
}
main start
outer start
inner
outer end
inner
main end
- 1
mainbegins. "main start" prints. - 2
outer()is called. Control jumps intoouter, which prints " outer start", then callsinner. - 3
inner()runs and returns to just after its call insideouter, which then prints " outer end" and returns tomain. - 4Back in
main.inner()is called again, then "main end" prints.
The order in which methods are written in a file has nothing to do with the order in which they run. Execution starts in main and moves to another method only when it is called. When predicting output, trace the calls from main, not the methods from the top of the file.
3void Methods
A void method does not have a return value and is therefore not called as part of an expression. Its return type in the header is the keyword void. It exists to perform a task: print something, change an object's state, or carry out a sequence of steps. A call to a void method is a statement by itself: printBanner();.
Because a void method produces no value, it cannot be stored in a variable, added to something, or passed as an argument. A common confusion is between printing a value and returning it: a void method that prints a sum shows it on the screen, but the calling code cannot use that sum in a calculation.
A void Method Cannot Be Used as a Value
Explain the compile error.
public static void printTotal(int a, int b)
{
System.out.println(a + b);
}
- 1A void method returns nothing.
printTotaldisplays a sum but gives no value back. - 2So there is nothing to store.
int result = printTotal(2, 3);asks for a value that does not exist, and the compiler rejects it. - 3Fix. Either call it as a statement,
printTotal(2, 3);, or rewrite it as a non-void method that returnsa + b.
A method that prints its result has not returned it. If the caller needs the value, for further arithmetic, a comparison, or storage, the method must be non-void and use return. Printed output goes to the screen; returned values go back to the code that called the method.
4Non-void Methods and Return Values
A non-void method returns a value that is the same type as the return type in its header. public static int square(int n) returns an int. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression: int area = square(6); or square(3) + square(4).
A non-void call can appear anywhere a value of its type is allowed: on the right side of an assignment, inside a println, as an argument to another method, or in a condition. Calling a non-void method as a statement by itself, without using its result, compiles but discards the value, which is almost always a mistake.
Using and Ignoring Return Values
Predict the output. Which call's result is lost?
public static int square(int n)
{
return n * n;
}
36
25
done
- 1Stored.
int area = square(6);stores the returned 36. - 2Used in an expression.
square(3) + square(4)adds the two returned values: 9 + 16 = 25. - 3Ignored.
square(10);computes 100 and returns it, but nothing stores or uses it, so the value disappears. This compiles, but it is almost always a mistake.
5Arguments Are Passed by Value
When calling methods, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments. Inside the method, the parameter is a separate variable: changing it has no effect on the variable the caller used as the argument.
This makes methods safe to call: a method cannot accidentally change the caller's primitive variables. When a method's purpose is to compute a new value for a variable, it should return that value and let the caller assign it, as in score = addBonus(score);. (With object references, the copied value is a reference, so a method can change the object both variables refer to, a subtlety that matters later when methods work with objects.)
Changing a Parameter Does Not Change the Argument
Predict the output.
public static void addTen(int n)
{
n = n + 10;
System.out.println("inside: " + n);
}
inside: 60
outside: 50
- 1The call copies 50 into
n.nandscoreare separate variables. - 2Inside the method.
nbecomes 60 and prints. - 3Back in main.
scorewas never changed; it still holds 50 (Figure 3). - 4To change
score, the method would have to return the new value and the caller would assign it:score = plusTen(score);.
inside: 60 then outside: 50. Arguments are passed using call by value, which initializes parameters with copies.Arguments That Do Not Fit
Given public static double pay(double hours, int rate), which calls compile?
public static double pay(double hours, int rate)
{
return hours * rate;
}
150.0
160.0
public static double pay(double hours, int rate)
{
return hours * rate;
}
- 1
pay(7.5, 20). Exact match: 150.0. - 2
pay(8, 20). Theint8 widens to thedouble8.0, which is allowed: 160.0. - 3
pay(20, 7.5). The second argument is adouble, but the second parameter is anint, and adoublecannot be narrowed automatically, so the call does not compile. - 4Number matters too.
pay(7.5)would fail because it supplies one argument for two parameters.
| Call | Compiles? | Reason |
|---|---|---|
pay(7.5, 20) | Yes | Exact types |
pay(8, 20) | Yes | int widens to double for the first parameter |
pay(20, 7.5) | No | double cannot be passed to the int parameter |
pay(7.5) | No | Too few arguments |
pay(7.5, 20, 1) | No | Too many arguments |
After addTen(score);, score is unchanged, because the method changed only its own copy. If the new value is needed, write a method that returns it and assign the result: score = plusTen(score);.
6Overloaded Methods
Methods are said to be overloaded when there are multiple methods with the same name but different signatures. Overloading lets related operations share a natural name: area(int side) for a square, area(int width, int height) for a rectangle, area(double radius) for a circle. System.out.println is itself heavily overloaded, with versions for int, double, boolean, String, and more, which is why it can print any type.
When an overloaded method is called, Java chooses the version whose parameter list matches the arguments' number, order, and types. If no version fits, the call does not compile. Overloads should all perform the same kind of task, so that a reader can understand any call from the method name alone.
Choosing Among Overloaded Methods
Predict each result.
public static int area(int side)
{
return side * side;
}
public static int area(int width, int height)
{
return width * height;
}
public static double area(double radius)
{
return 3.14 * radius * radius;
}
16
15
12.56
- 1
area(4). Oneintmatchesarea(int): 16. - 2
area(3, 5). Twointvalues matcharea(int, int): 15. - 3
area(2.0). Onedoublematchesarea(double): 3.14 × 2.0 × 2.0 = 12.56.
Parameters are declared in the method header (int side); arguments are the values in the call (4). Arguments supply values; parameters receive copies of them. Only the parameters' types and order matter for matching, never their names.
Four Habits for Method Calls
1. Jump and Return
A call runs the whole method, then resumes right after the call.
2. Use Every Return Value
Store it or use it in an expression; void methods return nothing.
3. Parameters Hold Copies
Changing a primitive parameter never changes the argument.
4. Match Number, Order, Type
Arguments must fit the parameter list; overloads are chosen this way.
A void method does not have a return value and is therefore not called as part of an expression. A non-void method returns a value of the same type as its return type, which must be stored in a variable or used as part of an expression. An argument is a value passed into a method when it is called; arguments must be compatible in number and order with the parameter types, and they are passed using call by value, which initializes the parameters with copies of the arguments. Methods are overloaded when multiple methods have the same name but different signatures. A method call interrupts sequential execution, runs the method's statements, and then returns control to the point immediately following the call.