AP Computer Science A · Study guide

Method Calls, Return Values, Arguments, and Overloading

AP® Computer Science A · Using Objects and Methods

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.

Big Picture

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.

TermMeaningExample
ArgumentA value passed into a method when it is called7.5 in pay(7.5, 20)
ParameterA variable in the method header that receives the argumentdouble hours
Call by valueParameters are initialized with copies of the argumentsChanging n does not change score
Return valueThe value a non-void method gives backsquare(6) returns 36
void methodA method with no return valueprintBanner()
OverloadingSeveral methods with the same name but different signaturesarea(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.

Figure 1. A method call interrupts the sequential execution of statements: the program runs the method's statements first, then returns to the point immediately following the call.
StepExecutingOutput so far
1main: println("A")A
2main: greet() calledA
3greet: println("B"), println("C")A B C
4greet ends; return to mainA B C
5main: println("D")A B C D
Worked Example 1 Flow of control

Tracing Calls Inside Calls

Predict the exact output order.

Code
public static void inner()
{
    System.out.println("  inner");
}

public static void outer()
{
    System.out.println(" outer start");
    inner();
    System.out.println(" outer end");
}
Output
main start
 outer start
  inner
 outer end
  inner
main end
  1. 1main begins. "main start" prints.
  2. 2outer() is called. Control jumps into outer, which prints " outer start", then calls inner.
  3. 3inner() runs and returns to just after its call inside outer, which then prints " outer end" and returns to main.
  4. 4Back in main. inner() is called again, then "main end" prints.
Result: The output has six lines in the order shown. Each call pauses the caller, runs the method completely, and resumes the caller immediately after the call.
Common Mistake 1 · Reading Methods in File Order

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.

Figure 2. A void method does not have a return value and is not called as part of an expression. A non-void method returns a value of its return type, which must be stored or used.
Worked Example 2 void methods

A void Method Cannot Be Used as a Value

Explain the compile error.

Code that does not compile
public static void printTotal(int a, int b)
{
    System.out.println(a + b);
}
  1. 1A void method returns nothing. printTotal displays a sum but gives no value back.
  2. 2So there is nothing to store. int result = printTotal(2, 3); asks for a value that does not exist, and the compiler rejects it.
  3. 3Fix. Either call it as a statement, printTotal(2, 3);, or rewrite it as a non-void method that returns a + b.
Result: A void method does not have a return value and therefore is not called as part of an expression. Printing a value and returning it are different things.
Common Mistake 2 · Treating Printing as Returning

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.

Worked Example 3 Return values

Using and Ignoring Return Values

Predict the output. Which call's result is lost?

Code
public static int square(int n)
{
    return n * n;
}
Output
36
25
done
  1. 1Stored. int area = square(6); stores the returned 36.
  2. 2Used in an expression. square(3) + square(4) adds the two returned values: 9 + 16 = 25.
  3. 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.
Result: The output is 36, 25, and done. To use the return value of a non-void method, it must be stored in a variable or used as part of an expression.

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.)

Figure 3. When calling a method, arguments are passed using call by value: each parameter is initialized with a copy of its argument, so changing the parameter does not change the caller's variable.
Worked Example 4 Call by value

Changing a Parameter Does Not Change the Argument

Predict the output.

Code
public static void addTen(int n)
{
    n = n + 10;
    System.out.println("inside: " + n);
}
Output
inside: 60
outside: 50
  1. 1The call copies 50 into n. n and score are separate variables.
  2. 2Inside the method. n becomes 60 and prints.
  3. 3Back in main. score was never changed; it still holds 50 (Figure 3).
  4. 4To change score, the method would have to return the new value and the caller would assign it: score = plusTen(score);.
Result: The output is inside: 60 then outside: 50. Arguments are passed using call by value, which initializes parameters with copies.
Worked Example 5 Argument compatibility

Arguments That Do Not Fit

Given public static double pay(double hours, int rate), which calls compile?

Calls that compile
public static double pay(double hours, int rate)
{
    return hours * rate;
}
Output
150.0
160.0
Call that does not compile
public static double pay(double hours, int rate)
{
    return hours * rate;
}
  1. 1pay(7.5, 20). Exact match: 150.0.
  2. 2pay(8, 20). The int 8 widens to the double 8.0, which is allowed: 160.0.
  3. 3pay(20, 7.5). The second argument is a double, but the second parameter is an int, and a double cannot be narrowed automatically, so the call does not compile.
  4. 4Number matters too. pay(7.5) would fail because it supplies one argument for two parameters.
Result: The first two calls compile and print 150.0 and 160.0; the swapped call does not compile. Arguments must be compatible in number and order with the parameter types.
CallCompiles?Reason
pay(7.5, 20)YesExact types
pay(8, 20)Yesint widens to double for the first parameter
pay(20, 7.5)Nodouble cannot be passed to the int parameter
pay(7.5)NoToo few arguments
pay(7.5, 20, 1)NoToo many arguments
Common Mistake 3 · Expecting a Method to Change the Caller's Variable

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.

Figure 4. Methods are overloaded when there are multiple methods with the same name but different signatures. Each call runs the version whose parameters match its arguments.
Worked Example 6 Overloading

Choosing Among Overloaded Methods

Predict each result.

Code
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;
}
Output
16
15
12.56
  1. 1area(4). One int matches area(int): 16.
  2. 2area(3, 5). Two int values match area(int, int): 15.
  3. 3area(2.0). One double matches area(double): 3.14 × 2.0 × 2.0 = 12.56.
Result: The results are 16, 15, and 12.56. Overloaded methods share a name but have different signatures, and the arguments decide which one runs.
Common Mistake 4 · Mixing Up Arguments and Parameters

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.

Core Synthesis

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.