Computer Fundamentals and Introduction to Programming · Lecture Notes

Chapter 9: Methods

As a program grows, the same jobs start to be written again and again in different places, and the main method becomes too long to read. A method gathers a task under a name. The task is written once and then called by name wherever it is needed. These notes first show how a method is defined and called. Next comes what happens in memory during a call: arguments being copied into parameters, the frame opened for each call, and the call stack these frames form. Return values, void methods and early return are treated separately. Why Java always passes arguments by value is shown step by step with the swap example. The real error messages given by the compiler for overloading, variable-length arguments, scope and shadowing are also examined. The last sections cover good method design and example methods such as even/odd, digit count, primality, GCD and LCM. All the programs in the notes were compiled and run with JDK 21.

Learning outcomes

Defining
Write the header and body of a method; call a method from main and from other methods; explain the signature of the main method and the meaning of the static modifier.
Data flow
Tell a parameter from an argument; use a return value in an expression; use a void method and early return in the right places; show by tracing that Java passes arguments by value; work with overloading and variable-length arguments.
Scope
Explain where a local variable is visible and how long it lives; trace the frames on the call stack step by step; recognize shadowing and scope-related compile errors.
Design
Split a problem into single-purpose methods; write a method's contract; build short, focused, testable methods that return their result instead of printing it.

9.1What is a method?

In the Java programs written so far, all the work was done in one place, inside the main method. In short programs this is enough. But when a program reaches a few hundred lines, the same computation gets rewritten in three or four places. When a bug is fixed, the other copies are forgotten. What main does, and in what order, also becomes unreadable. Methods are the solution to this problem.

9.1.1Naming a task

In mathematics, a function produces an output for its input: for f(x) = x², f(3) = 9. A function in programming is a similar unit. A piece of code that does a particular task is given a name. This code takes its inputs from outside, does its job and, if necessary, gives a result. Since everything in Java is written inside a class, functions are defined inside a class too, and they are called methods.

Definition 9.1

A method is a named group of statements defined inside a class that does a particular task. A method receives its inputs through its parameters and gives its result as its return value. A method is run by writing its name followed by values in parentheses; this is called a method call.

The methods in Java's own library illustrate this idea well. The call Math.sqrt(16) gives the square root of 16, that is, 4.0. You do not need to know how the square root is computed. Three things need to be known: the name of the method (sqrt), what it asks for (a number) and what it gives (the square root). The internal details are hidden from the user of the method. Figure 9.1 shows this as a black box.

input53add(a, b)output8parametersbody (details hidden)return value
Figure 9.1: A method is like a black box. add takes two inputs (5 and 3) and gives one result (8). The inputs enter through the parameters and the result leaves as the return value; the details in the body are not visible from outside.

The box in the figure has two inputs on its left and one output on its right. What is inside the box can be seen only by looking at the body of the method. The code that calls the method thinks only “give it these two numbers and get the sum back”. This separation is the most important gain of methods: what a task does is separated from how it does it.

9.1.2Why write methods?

Suppose a student is writing a program that prints the grades of three courses on the screen. The student wants to draw a line before and after each course. Without methods, the loop that draws the line is copied six times. If the length of the line were to change, all six places would have to be corrected; if one is forgotten, the output is inconsistent. If this loop is put into a method named drawLine, a one-line call remains in each of the six places: drawLine(5);. If the length changes, only the argument changes.

The gains of writing methods can be listed as follows:

  • Avoiding repetition. The same code is written once. When a bug is found, it is fixed in one place and the fix applies to every call.
  • Readability. A well-named method call says what is being done. The line if (isPrime(n)) is much easier to read than a loop looking for divisors.
  • Testability. A small method can be tried with a few sample inputs independently of the rest of the program. That digitCount(-507) gives 3 can be checked in a single line.
  • Reuse. A method written once is used in other programs and inside other methods. A method that computes the LCM shortens its work by calling the GCD method.
  • Division of labor. A big problem is split into small subtasks. Each subtask becomes a separate method and is written and tried separately.

9.1.3What happens in a call?

When a method is called, the flow of the program temporarily leaves the place that made the call, goes into the body of the method, and returns to where it left off when the method ends. Figure 9.2 shows this round trip.

mainint x = 5;int t = add(x, 3);System.out.println(t);addstatic int add(int a, int b) { return a + b;}① call: a = 5, b = 3② return 8 → 8 takes the place of the call③ main continues where it left off: t = 8, then println
Figure 9.2: The journey of a call. (1) main calls add(x, 3); control passes to the method and a = 5, b = 3. (2) return sends 8 back; 8 takes the place of the call. (3) main carries on where it left off: t becomes 8, then println runs.

This journey consists of the same five steps in every call:

  1. The arguments are evaluated. The values of the expressions inside the parentheses of the call are found. In add(x, 3), the current value of x (5) is read.
  2. The values are copied into the parameters. A new area of memory is opened for the method. The first value is written into the first parameter and the second value into the second parameter: a = 5, b = 3.
  3. The body runs. The statements between the curly braces of the method run in order.
  4. A value is returned. When the return statement is reached, the method ends and the value next to return is sent to the place that called it.
  5. The calling code continues. The returned value takes the place of the call expression. The program continues from the line where the call is.

One point in these steps must not be overlooked: each call works with its own parameters and its own local variables. If the same method is called twice, two separate areas of memory are opened. The second call does not see the variables of the first; when the first call ends, its variables have already been deleted. Pass by value, scope and the call stack all rest on this rule.

9.2Method definition and call

To use a method, you must first define it, that is, write its name, its inputs, the type of its result and its body. A defined method is then called wherever you like and as many times as you like. The definition is made once, the call many times.

9.2.1The first method: add

The add method, which gives the sum of two integers, and the two lines that use it, look like this:

static int add(int a, int b) {
    int sum = a + b;
    return sum;
}

int total = add(5, 3);
System.out.println(total);

The first four lines are the definition. The line static int add(int a, int b) is the header of the method. int says that the method will return an integer. add is the name of the method. The int a, int b inside the parentheses declare that the method expects two integers and that they will be reached inside the method under the names a and b. The two lines between the curly braces are the body of the method: first a + b is written into a variable named sum, and then this value is given back with return. The last two lines are the call: add(5, 3) runs the method with 5 and 3, and the returned value is assigned to total and printed.

These fragments do not compile on their own; they must be inside a class. The complete program is below. The method is written inside the same class as main, outside main. Methods cannot be defined inside one another: writing add inside the curly braces of main is a compile error.

public class Add {
    static int add(int a, int b) {
        int sum = a + b;
        return sum;
    }

    public static void main(String[] args) {
        int total = add(5, 3);
        System.out.println(total);
    }
}
8

The program always starts running from main. Even if add is written before main in the class, it does not run on its own; it runs only when it is called. The order of methods within the class does not matter. add could just as well have been written below main.

The a and b in the definition and the 5 and 3 in the call play different roles and have different names.

Definition 9.2

A parameter, or more fully a formal parameter, is a variable declared with its type in the method header; it says which inputs the method expects. An argument, or actual argument, is a value written inside the parentheses at the time of the call and copied into the parameter.

int total = add(5, 3);add(5,3)actual argumentsvalue is copied53abformal parameterssum = 5 + 3 = 8returntotal = 8
Figure 9.3: In the call int total = add(5, 3);, the actual arguments (5 and 3) are copied into the formal parameters (a and b). In the body sum = 5 + 3 = 8 is computed, and return sends 8 to total.

A parameter is a variable; an argument is a value, or an expression whose value is to be computed. Parameters come to life anew each time the method is called and are filled with the arguments of that call. Arguments are matched to parameters in order: the first argument to the first parameter, the second argument to the second. The number of arguments must equal the number of parameters, and the type of each argument must fit the corresponding parameter. The calls add(5) and add(5, 3, 1) do not compile, because add expects exactly two integers.

public class MissingArgument {
    static int add(int a, int b) { return a + b; }
    public static void main(String[] args) {
        System.out.println(add(5));
    }
}
MissingArgument.java:4: error: method add in class MissingArgument cannot be applied to given types;
        System.out.println(add(5));
                           ^
  required: int,int
  found:    int
  reason: actual and formal argument lists differ in length
1 error

This time the compiler gives a longer message: the method add cannot be applied to the given types. The line required: int,int shows the parameter types the method expects, and found: int shows the arguments found in the call. The last line gives the reason: the actual and formal argument lists differ in length.

Common mistake

Rewriting the type of the argument in the call: add(int 5, int 3). Types are written only in the definition, next to the parameters. In a call there are only values or expressions: add(5, 3). Conversely, forgetting the parameter type in the definition is also an error: static int add(a, b) does not compile. Each parameter's own type is written separately; the form int a, b is not valid in a parameter list.

9.2.2Using the result of a call

The call of a method that returns a value is an expression in Java. After the call runs, the returned value takes its place. So a call can be used anywhere a value can be used: on the right of an assignment, inside an arithmetic operation, in a condition, or as an argument to another method. The following program shows four different uses together:

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

    public static void main(String[] args) {
        int x = 5;
        int t = add(x, 3);                     // a variable and a constant as arguments
        System.out.println(t);
        System.out.println(add(10, 20) * 2);   // the call is part of an expression
        System.out.println(add(add(1, 2), 4)); // the result of a call is an argument to another call
        add(7, 8);                             // the returned value is not used
    }
}
8
60
7

The first call takes a variable and a constant as arguments. Since the value of x is 5, add(5, 3) = 8 is computed. In the second call, add(10, 20) first returns 30, then this value is multiplied by 2 and 60 is printed. In the third line the result of one call becomes an argument to another call. Java first runs the inner add(1, 2) and gets 3; then the outer call runs as add(3, 4) and 7 is printed.

The add(7, 8); in the last line is also a valid statement. The method returns 15, but since this value is not used anywhere, it is discarded. Java does not require the returned value to be used. However, this line adds nothing to the program: add only computes; it does not print anything and does not change any variable. If a method that returns a value is called and its result is thrown away, this is usually a sign of forgetfulness.

If there are several calls in one expression, Java evaluates the arguments and operands from left to right. The small method below prints its argument in square brackets, so that you can tell it has been called, and returns twice its argument:

public class OrderDemo {
    static int twice(int x) {
        System.out.print("[" + x + "] ");
        return 2 * x;
    }

    public static void main(String[] args) {
        int r = twice(3) - twice(1);
        System.out.println(r);
        System.out.println(twice(twice(1)));
    }
}
[3] [1] 4
[1] [2] 4

In the expression twice(3) - twice(1), the call on the left runs first and prints [3], then the one on the right runs and prints [1]. The subtraction is done when both values are ready: 6 − 2 = 4. In the nested call on the last line, the inner twice(1) must run first, because it provides the argument of the outer call. [1] is printed first, then [2], and 4 is printed. Printing to the screen and returning a value are independent of each other. Whatever the method prints, only its return value takes part in the expression.

9.2.3add(5, 3) step by step

To see in detail what happens in a call, the code is executed line by line. The line numbers refer to the code below; lines 7 and 8 are inside main.

static int add(int a, int b) {
    int sum = a + b;
    return sum;
}

// in main:
int total = add(5, 3);
System.out.println(total);

Table 9.1 gives, at each step, which line is running, which frames are open in memory and the variables in the topmost frame. A frame is the area of memory set aside for one call; its exact definition is given together with the call stack.

Table 9.1: The trace table of the call add(5, 3). In the call stack column the topmost frame is written first.
StepLineCall stack (top first)Variables (top frame)Output
17main()——
21add(5, 3) ← main()a=5, b=3—
32add(5, 3) ← main()a=5, b=3, sum=8—
43add(5, 3) ← main()a=5, b=3, sum=8—
57main()total=8—
68main()total=88

Execution starts at line 7 in main. A value cannot be written into total before the right side of the assignment has been computed. Since the right side has a call, that must run first. In step 2 a new frame is opened for add and the arguments are copied: a = 5, b = 3. In step 3 the local variable sum is created and gets the value 8. This variable lives only in the frame of add; main cannot see it. In step 4 return sum; runs, 8 is sent to the caller and the frame of add is closed. In step 5 execution returns to line 7. 8 has taken the place of the call and the assignment is completed: total = 8. At this point a, b and sum no longer exist. In step 6 the 8 is printed.

main()total = add(5, 3)adda5b3 main()total = add(5, 3)adda5b3sum8closedreturn 8 main()total8total = 8
Figure 9.4: Three moments of the call add(5, 3). (a) The frame of add has been opened above main: a = 5, b = 3. (b) return 8: the frame is closing. (c) Back in main: total = 8; a, b and sum no longer exist.

A detail in the trace table deserves attention: line 7 appears twice. The first time is when the call starts, and the second is when the assignment is completed after the call ends. A line being “left unfinished” and then resumed is a natural consequence of method calls. When execution meets a call, it suspends the line it is on, finishes the method and comes back to the same line.

9.3The call stack

In the add example there were only two methods: main and add. In real programs a method calls another method, and that one calls yet another. At one moment several methods are left “half done”, waiting. Java keeps track of which method is where, and which variables belong to whom, with a stack structure.

9.3.1Stack and frame

Think of plates stacked on top of one another in a cafeteria. A new plate is always put on top, and a plate is always taken from the top. The last plate put on is the first one taken. This arrangement is called last in, first out, and a structure that behaves this way is called a stack. Method calls open and close in exactly this order.

Definition 9.3

A stack frame is the area of memory set aside for a method call. The frame holds the parameters and local variables of that call and the information about where execution should return when the method ends. The call stack is the stack made up of the frames of all the calls currently in progress. Each call puts a new frame on top of the stack; when the method ends, the top frame is removed.

When the program starts, there is a single frame on the stack: the frame of main. When main calls a method, the frame of that method is put on top of main's. If that method calls another, the stack rises one level further. Two rules follow from this arrangement. First, only the method of the topmost frame runs; the ones below wait for the call above them to finish. Second, the method called last finishes first. A method cannot finish before the method it called finishes.

9.3.2avg(9, 7) step by step

In the following example, the avg method calls the add method to find the average of two numbers. So there are three frames on the stack at once:

static int add(int a, int b) {
    return a + b;
}
static int avg(int x, int y) {
    int t = add(x, y);
    return t / 2;
}
int o = avg(9, 7);  // in main
System.out.println(o);

Line numbers: 1–3 are add, 4–7 are avg, and 8–9 are the two lines in main. Table 9.2 gives the nine steps.

Table 9.2: The trace table of the call avg(9, 7). In steps 4 and 5 there are three frames on the stack.
StepLineCall stack (top first)Variables (top frame)Output
18main()——
24avg(9, 7) ← main()x=9, y=7—
35avg(9, 7) ← main()x=9, y=7—
41add(9, 7) ← avg(9, 7) ← main()a=9, b=7—
52add(9, 7) ← avg(9, 7) ← main()a=9, b=7—
65avg(9, 7) ← main()x=9, y=7, t=16—
76avg(9, 7) ← main()x=9, y=7, t=16—
88main()o=8—
99main()o=88

In step 1, main calls avg(9, 7); there is still a single frame on the stack. In step 2 the frame of avg is put on top of main and the arguments are copied: x = 9, y = 7. In step 3, avg itself makes a call on line 5: add(x, y). What is sent is not the variables x and y themselves but their values: 9 and 7. In step 4 the frame of add is put on top and there are three frames. At this moment only add runs. avg waits on line 5, and main on line 8.

In step 5, add returns 16 and its frame is removed. The frame opened last has closed first. In step 6 execution returns to line 5 of avg: 16 takes the place of the call and t = 16. In step 7, return t / 2; runs. The quotient of two integers is integer division: 16 / 2 = 8. The frame of avg closes too. In step 8 execution returns to main and o = 8. At this moment none of the variables x, y, t, a and b exists any more. In step 9, 8 is printed.

main()o = avg(9, 7)avgx9y7 main()o = avg(9, 7)avgx9y7t = add(x, y)adda9b7
main()o = avg(9, 7)avgx9y7t = add(x, y)adda9b7closedreturn 16 main()o = avg(9, 7)avgx9y7t16closedreturn 8
Figure 9.5: Four moments of the call stack. (a) The frame of avg is above main: x = 9, y = 7. (b) add is on top; there are three frames on the stack. (c) add returns 16 and closes. (d) avg returns 8 and closes; only main will remain on the stack again.

The whole program and its real output are below. The call avg(9, 8) on the second line shows the effect of integer division: 9 + 8 = 17 and 17 / 2 = 8. Although the real average is 8.5, the return type is int and the division is between two ints, so the fraction is discarded.

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

    static int avg(int x, int y) {
        int t = add(x, y);
        return t / 2;
    }

    public static void main(String[] args) {
        int o = avg(9, 7);
        System.out.println(o);
        System.out.println(avg(9, 8));
    }
}
8
8
Common mistake

Taking the same names in different methods to be the same variable. The x of avg and an x in main, or the a of add and the a of another method, are completely independent of one another. Each is a separate box of memory in its own frame. A value passes from one method to another in only two ways: as an argument in a call, or as a return value with return.

9.3.3Rules of the stack

The call stack is not specific to Java; method or function calls in C, Python and almost every programming language work in the same way. If the following rules are kept in mind while tracing, the answer to most questions follows on its own:

  • Every call opens a new frame. If the same method is called twice, two separate frames are opened, and the second call does not see the variables of the first.
  • Only the topmost frame runs. Every frame below it is in the middle of a call, waiting for the result of that call.
  • When a method ends, its frame is deleted with all its contents. Local variables and parameters do not carry values from one call to another.
  • The returned value takes the place of the call in the expression where the call was made, and the computation continues from there.
  • The last frame opened is the first to close. Frames close in the reverse of the order in which they were opened.

The stack also has a limit. Java sets aside a stack of limited size for each thread. If methods that call one another without end fill the stack, the program stops with a StackOverflowError. In ordinary programs the stack depth does not go beyond a few or a few dozen frames. The Method Call Stack simulator animates the opening and closing of frames step by step.

9.4The parts of a method definition

A method definition consists of two parts: the header and the body. The header is the face of the method that is visible to the outside world. It says who may call it, what it will return, its name and which inputs it expects. The body contains the statements that do the work of the method.

9.4.1Header and body

Figure 9.6 breaks the header public static int add(int a, int b) into its parts.

public static int add(int a, int b) {accesswho can call it?modifierno object neededreturn typewhat is returned?namename of the taskparameter listwhich inputs?int sum = a + b;return sum;}body: the statements that run when it is calledreturn supplies a value of the return typesignature = name + parametertypes: add(int, int)
Figure 9.6: The parts of a method definition: the access modifier (public), the modifier (static), the return type (int), the name (add), the parameter list (int a, int b) and the body between curly braces. The name and the parameter types together form the signature of the method: add(int, int).
Table 9.3: The parts of a method header and the questions they answer.
PartExampleQuestion answeredExplanation
access modifierpublicWho can call it?public can be called from anywhere, private only from the same class. If nothing is written, classes in the same package can call it.
modifierstaticIs an object needed?A static method belongs to the class; no object has to be created to call it.
return typeintWhat is returned?The type of the value the method gives. void if it does not return a value.
nameaddWhat is the name of the task?An identifier that says what the method does.
parameter list(int a, int b)Which inputs?“Type name” pairs separated by commas; empty parentheses () if there are no inputs.
body{ … }How is it done?The statements that run when it is called; return supplies a value of the return type.

The order of the parts in the header is fixed: first the access modifier and the modifier, then the return type, then the name and the parameter list. An order such as int static add(…) does not compile. The access modifier and static are optional; the return type, the name and the parentheses are required. In the examples in these notes, methods are written in the same class as main and as static. The access modifier is mostly left out, because the methods are called only from the same class anyway.

Definition 9.4

The method signature is the name of a method together with the list of its parameter types, written in order. The signature of the method static int add(int a, int b) is add(int, int). The return type, the parameter names and the modifiers are not part of the signature. A class cannot contain two methods with the same signature.

The signature is the information the compiler looks at when deciding which method to bind a call to. When the compiler sees the call add(5, 3), it looks for a method named add that accepts two ints. It is natural that the parameter names (a, b) are not in the signature, because these names never appear in a call. The return type is not in the signature either, because the call itself carries no hint about the type of the returned value.

9.4.2Method names

Method names follow the same rules as variable names: they start with a letter, may contain letters, digits and underscores, and cannot be one of Java's reserved words. By Java convention, method names start with a lowercase letter, and when several words are joined, the first letter of each later word is capitalized: digitCount, printPositive, max3. Letters outside the basic English alphabet are valid in Java, but they are often avoided so that files open without trouble on different computers.

A good method name says what the method does. Methods that perform an action are named with a verb: drawLine, writeReport, readGrades. Methods that compute a value take the name of that value: average, area, gcd. Methods that return boolean read like a question: isEven, isPrime. When a method named this way is used in a condition, the line reads almost like plain English: if (isPrime(n)), “is n prime?”.

9.4.3The main method and static

The main found in every Java program is also a method, and every word in its header has a reason.

Table 9.4: The parts of the header public static void main(String[] args).
PartWhy?
publicSo that the JVM (Java Virtual Machine) can call the method from outside the class.
staticSo that the method can be called without creating any object.
voidmain does not return a value.
mainThe name the JVM looks for in order to start the program.
String[] argsThe arguments given on the command line when the program is run.

The meaning of the static modifier is as follows. Java is an object-oriented language; most methods belong to an object and are called through that object. A static method, on the other hand, belongs not to an object but to the class itself. No object has to be created first in order to call it. When the JVM starts the program, there are no objects yet. For it to be able to run main, this method must not need an object; that is, it must be static.

This has a consequence: a static method cannot directly use a non-static method or field of the same class, because there is no object to which that method would belong. Below is the example showing this error inside a complete class, together with the message given by the JDK 21 compiler:

public class Demo {
    void greet() { }
    public static void main(String[] args) {
        greet();   // error
    }
}
Demo.java:4: error: non-static method greet() cannot be referenced from a static context
        greet();   // error
        ^
1 error

The message says “the non-static method greet() cannot be referenced from a static context”. The compiler shows the line of the error (Demo.java:4) and its place with the ^ mark. Within the scope of these notes, the fix is simple: make the called method static too.

public class StaticFix {
    static void greet() {
        System.out.println("Hello");
    }

    public static void main(String[] args) {
        greet();
    }
}
Hello

The parameter String[] args of main receives the words typed on the command line when the program is run, as an array. The following program prints how many arguments arrived and the arguments themselves.

public class MainArgs {
    public static void main(String[] args) {
        System.out.println(args.length);
        for (String a : args) System.out.println(a);
    }
}

When run without arguments with the command java MainArgs, args is an empty array and the program prints only 0. When run with java MainArgs Ali 42, the output is:

2
Ali
42

Each word on the command line arrives as a separate String. 42 is not a number but a text of two characters.

Common mistake

Writing the header of main incompletely or differently. If static is forgotten or the name is written Main, the program may compile, but when it is run the JVM cannot find the starting point and does not start the program. Java is case-sensitive: main and Main are two different names.

9.5The return value

When a method finishes its work, it can give the caller a result, or it can simply do a job without giving anything back. Which of the two it does is determined by the return type in the header. The result is given with the return statement.

9.5.1The return statement

Definition 9.5

The return type is the type of the value the method gives; it is written in front of the name in the header. The return value is the value the method sends to the caller with a return statement. The statement return expression; computes the value of the expression, ends the method at once and returns this value to the place where the call was made.

return does two jobs at once: it sends a value and it ends the method. Statements written after return on the same path do not run. The compiler rejects a statement that comes immediately after return and can never be reached by any path with an “unreachable statement” error.

The type of the returned value must match the return type. A method that returns int can write return 8; but cannot write return "eight";. If the return type is double, return 8; is valid; the int value is widened to double automatically and 8.0 goes to the caller. The reverse is not valid: a method that returns int cannot write return 2.5;, because the fractional part would be lost.

9.5.2void methods

Not every method has to compute a value. A method that draws a line on the screen, writes a report or adds a record to a file has no result to send to the caller. The return type of these methods is void. void means “empty”: the method does not return a value to the call.

static void drawLine(int n) {
    for (int i = 0; i < n; i++)
        System.out.print("-");
    System.out.println();
}
// in main:
drawLine(5);           // -----
int x = drawLine(5);   // ERROR: void has no value

The drawLine method prints n dashes and ends the line. The method's job is a side effect: it changes the state of the screen but gives the caller no value. The complete program and its output:

public class DrawLine {
    static void drawLine(int n) {
        for (int i = 0; i < n; i++)
            System.out.print("-");
        System.out.println();
    }

    public static void main(String[] args) {
        drawLine(5);
        System.out.println("Methods");
        drawLine(8);
        drawLine(0);
        System.out.println("end");
    }
}
-----
Methods
--------

end

drawLine(5) prints five dashes and drawLine(8) eight. In the call drawLine(0) the loop never runs; only println() runs, and an empty line appears in the output. The last line in the example, int x = drawLine(5);, does not compile. Because the method gives no value, it cannot be used on the right of an assignment:

VoidAssign.java:9: error: incompatible types: void cannot be converted to int
        int x = drawLine(5);   // ERROR: void has no value
                        ^
1 error

The message says “incompatible types: void cannot be converted to int”. For the same reason, a void call cannot be an argument to another method either:

public class VoidPrint {
    static void drawLine(int n) {
        System.out.println("-".repeat(n));
    }
    public static void main(String[] args) {
        System.out.println(drawLine(5));
    }
}
VoidPrint.java:6: error: 'void' type not allowed here
        System.out.println(drawLine(5));
                                   ^
1 error

This time the compiler says “void type not allowed here”. The rule is a single one: a void call can be written only as a statement on its own, with a semicolon at the end. It cannot be part of an expression.

add(5, 3)return8int t = 8;the value takes the place of the calldrawLine(5)-----prints to the screen (side effect), returns no valueint x = drawLine(5); ✗
Figure 9.7: A method that returns a value and one that does not. The 8 returned by add(5, 3) takes the place of the call and is used in the assignment. drawLine(5) only prints to the screen; its result cannot be assigned to a variable.

In a void method return is not required. The method ends by itself when it reaches the closing curly brace of its body. Even so, a valueless return; statement can be written in a void method. This statement sends no value; it only ends the method at that point. The early-return pattern is based on this statement.

Common mistake

Thinking that a result must be both printed and returned, or mixing the two up. System.out.println(x) prints the value to the screen but sends nothing to the caller. return x; sends the value to the caller but prints nothing to the screen. Methods that compute should return the result and leave the decision to print to the caller.

9.5.3Early return

For some inputs the method has nothing to do. This case is caught at the start of the method and the method is left at once. This way the real work is written in a flat sequence, not buried inside nested if blocks.

Definition 9.6

Early return is catching a special case with a condition at the start of the method and ending the method with return before it reaches the end of the body. In a void method a valueless return; is used, and in a method that returns a value, return with a value suitable for that case.

static void printPositive(int num) {
    if (num <= 0) return;
    System.out.println(num);
}

printPositive prints only positive numbers. If the number is 0 or negative, return; ends the method at once and println is never reached. Figure 9.8 shows these two paths with a flow diagram.

printPositive(num)num <= 0 ?yesreturn;early exitnoprintln(num);the method endsprintPositive(-3) → no outputprintPositive(7) → 7
Figure 9.8: The flow of printPositive. If num <= 0, the Yes branch leaves the method early with return;; otherwise the number is printed and the method reaches its end. printPositive(-3) prints nothing and printPositive(7) prints 7.

In the following program the method is called twice: first with −3, then with 7. Line numbers: 1–4 are the method, and 6 and 7 are the two calls in main. Table 9.5 traces the two calls one after the other.

static void printPositive(int num) {
    if (num <= 0) return;
    System.out.println(num);
}
// in main:
printPositive(-3);
printPositive(7);
Table 9.5: The trace table of the calls printPositive(-3) and printPositive(7).
StepLineCall stack (top first)Variables (top frame)Output
16main()——
21printPositive(-3) ← main()num=−3—
32printPositive(-3) ← main()num=−3—
47main()——
51printPositive(7) ← main()num=7—
62printPositive(7) ← main()num=7—
73printPositive(7) ← main()num=77
84printPositive(7) ← main()num=77

In the first call a frame is opened and num = −3. On line 2, −3 <= 0 is true and return; runs. The method ends at once; the println on line 3 is never reached and the output stays empty. main continues from the next line, the second call. The second call opens a brand-new frame: num = 7. The num variable of the previous call was deleted long ago; the two calls have no variable in common. This time 7 <= 0 is false, there is no early return and 7 is printed. In the last step execution reaches the closing curly brace on line 4; the void method returns by itself here. If a call printPositive(0) is added to the full program, the output does not change, because 0 is also caught by the early return:

public class PrintPositive {
    static void printPositive(int num) {
        if (num <= 0) return;
        System.out.println(num);
    }

    public static void main(String[] args) {
        printPositive(-3);
        printPositive(7);
        printPositive(0);
    }
}
7

Without early return, the same method would be written as if (num > 0) { System.out.println(num); }. For a one-line job there is little difference between the two forms. But if the real work takes ten lines and there are three different special cases, the form without early return gives three levels of nested if. With early return, each special case is filtered out in one line at the start of the method, and the real work stays unindented.

Early return is also often used in methods that return a value. In that case the right value for that special case is written next to return. The line if (rest == 0) return 1; in the digit-count method and the line if (n < 2) return false; in the prime method are early returns.

9.5.4return and type errors

The compiler checks that a method that returns a value really does return a value in every case. In the first example below the method returns a value only when n is positive:

public class MissingReturn {
    static int check(int n) {
        if (n > 0) {
            return 1;
        }
    }
}
MissingReturn.java:6: error: missing return statement
    }
    ^
1 error

The message says “missing return statement” and points to the closing curly brace of the method. The compiler thinks like this: if n is not positive, the if is not entered and execution reaches the end of the method. On this path there is no value to return. In a method that is not void, every path must end with a return. The fix is to close the missing path: add return 0; at the end of the method, or write an else branch for the if and return a value there too.

The compiler does this check without looking at the value of the condition. Even if if (n > 0) return 1; if (n <= 0) return 0; is written, the result does not change. For a human the two conditions cover all cases, but the compiler sees only two separate ifs and gives the same error. The way to convince the compiler is to use if-else or to put an unconditional return at the end of the method.

The second kind of error is a returned value that does not fit the return type:

public class LossyConversion {
    static int f() {
        return 2.5;
    }
}
LossyConversion.java:3: error: incompatible types: possible lossy conversion from double to int
        return 2.5;
               ^
1 error

The message says “incompatible types: possible lossy conversion from double to int”. Java does not perform narrowing conversions, which can lose information, by itself. If the programmer really wants the fraction discarded, this is stated with an explicit cast: return (int) 2.5; compiles and returns 2. If a fractional result is wanted, the return type is made double.

There are two more cases where return and the return type do not agree. A void method cannot return a value, and a valueless return; cannot be written in a method that returns a value:

public class VoidReturn {
    static void g() {
        return 1;
    }
}
VoidReturn.java:3: error: incompatible types: unexpected return value
        return 1;
               ^
1 error
public class NoReturnValue {
    static int h() {
        return;
    }
}
NoReturnValue.java:3: error: incompatible types: missing return value
        return;
        ^
1 error
Table 9.6: Compile errors related to return (JDK 21 messages) and their fixes.
SituationMessageFix
No return on one pathmissing return statementadd a return to the missing branch or at the end of the method
return 2.5; in an int methodincompatible types: possible lossy conversion from double to intan explicit cast with (int), or make the return type double
return 1; in a void methodincompatible types: unexpected return valueremove the value or change the return type
return; in an int methodincompatible types: missing return valuewrite a value after return
Assigning a void callincompatible types: void cannot be converted to intrewrite the method so that it returns a value
Using a void call as an argument'void' type not allowed herewrite the call as a separate statement
Example 9.1

A method sign that returns the sign of a number as −1, 0 or 1 has been written like this: static int sign(int x) { if (x > 0) return 1; else if (x < 0) return -1; }. Does it compile?

It does not. For x = 0 both conditions are false and execution reaches the end of the method without a return. The compiler gives the error missing return statement. Once else return 0; is added at the end of the chain, or return 0; at the end of the method, every path ends with a value: sign(5) = 1, sign(−3) = −1, sign(0) = 0.

9.6Passing parameters

In a call the value of the argument passes to the parameter. But if the method changes its parameter, does the caller's variable change too? The answer to this question is definite in Java, and it surprises many new programmers.

9.6.1Pass by value

Definition 9.7

Pass by value means that in a call the value of the argument is copied and written into the parameter. The parameter is a separate box of memory from the argument. Whatever the method does to its parameter, the caller's variable is not affected. Java always passes arguments by value.

For primitive types such as int, double, boolean and char, what is passed is the number or the character itself. The caller's variable and the method's parameter are two separate boxes; at the moment of the call, a copy of what is in the first is written into the second. After the copying, the two boxes are independent of each other.

main()num5inc(num)x5value is copied
Figure 9.9: In the call inc(num), the value (5) of the num box in main is copied into the x box in the frame of inc. There are two separate boxes of memory.

For objects, for example arrays, the situation looks different at first sight. An array variable does not contain the array itself but a reference that shows where the array is in memory. When an array is sent to a method, it is this reference that is copied. Because the copied reference points to the same array, the method can change the elements of the array. But this is also pass by value: the value copied is a reference. If the method assigns a new array to its parameter, the caller's variable still points to the old array.

9.6.2inc(num) step by step

The first example is a void method that tries to increase a number:

static void inc(int x) {
    x++;
}
// in main:
int num = 5;
inc(num);
System.out.println(num);   // 5

Line numbers: 1–3 are inc and 5–7 are the lines in main. When the program is run, it prints 5, not 6:

5
Table 9.7: The trace table of the call inc(num). x changes; num does not.
StepLineCall stack (top first)Variables (top frame)Output
15main()num=5—
26main()num=5—
31inc(5) ← main()x=5—
42inc(5) ← main()x=6—
53inc(5) ← main()x=6—
67main()num=55

In step 1, num = 5 in the frame of main. In step 2, inc(num) is called. What is sent is not the variable num but its value, 5. In step 3 a separate box is opened in the new frame: x = 5. This is a copy. In step 4, x++ runs and x = 6. Only the box of inc has changed; num in main is still 5. In step 5 the method ends, and the frame and the x (6) inside it are deleted. Because inc is a void method, the value 6 is sent nowhere and is lost completely. In step 6 the value of num, 5, is printed.

main()num5incx5copy main()num5incx6
Figure 9.10: (a) The moment of the call: x = 5 in the frame of inc, a copy of num. (b) After x++: x = 6, but num in main is still 5.

9.6.3The swap trap

Exchanging the values of two variables, that is, swapping them, is a frequent job in programming. A swap is done in three steps with a temporary variable. Putting these three steps into a method looks reasonable:

static void swap(int a, int b) {
    int t = a;
    a = b;
    b = t;
}
// in main:
int x = 3, y = 5;
swap(x, y);
System.out.println(x + " " + y);   // 3 5

As the comment line shows, the program prints 3 5, not 5 3. The swap inside the method is correct, but what is swapped is not x and y themselves but their copies. Table 9.8 shows the situation step by step. Line numbers: 1–5 are swap and 7–9 are the lines in main.

Table 9.8: The trace table of the call swap(x, y). a and b are swapped; x and y do not change.
StepLineCall stack (top first)Variables (top frame)Output
17main()x=3, y=5—
28main()x=3, y=5—
31swap(3, 5) ← main()a=3, b=5—
42swap(3, 5) ← main()a=3, b=5, t=3—
53swap(3, 5) ← main()a=5, b=5, t=3—
64swap(3, 5) ← main()a=5, b=3, t=3—
79main()x=3, y=53 5

At the moment of the call a = 3 and b = 5; these are copies of x and y and have no connection with them. int t = a; puts 3 into the temporary box. With a = b;, a = 5; the old value of a is now kept only in t. With b = t;, b = 3. At this point the boxes of swap have really swapped: a = 5, b = 3. But when the method ends, a, b and t are all deleted. The x and y in main have not been touched at all: x = 3, y = 5.

main()x3y5swap(x, y)swapa5b3t3
Figure 9.11: After the last line of swap: in the frame of swap, a = 5, b = 3, t = 3; in the main frame below, x = 3, y = 5. The swap has happened only in the copies.

This can also be seen by adding a few print lines inside the method. The version below prints its own variables at the start and the end of the method, and the variables of main after the return:

public class SwapTrace {
    static void swap(int a, int b) {
        System.out.println("swap start: a=" + a + " b=" + b);
        int t = a;
        a = b;
        b = t;
        System.out.println("swap end: a=" + a + " b=" + b + " t=" + t);
    }

    public static void main(String[] args) {
        int x = 3, y = 5;
        swap(x, y);
        System.out.println("main: x=" + x + " y=" + y);
    }
}
swap start: a=3 b=5
swap end: a=5 b=3 t=3
main: x=3 y=5

The second line of the output shows that the swap succeeded inside the method, and the third line shows that it had no effect outside. In Java it is impossible to write a method that swaps two primitive variables. The swap is either done in the calling code, with a temporary variable, or the values are kept in an array and the elements of the array are swapped.

Common mistake

Thinking that because the parameter and the argument have the same name, the method will change the caller's variable. Even if static void inc(int num) { num++; } is written and inc(num); is called in main, the result does not change. Even if the parameter's name is num, it is a separate box in the frame of inc. Having the same name does not tie the two variables together.

9.6.4Passing the result back to the caller

If a method wants to change a variable of the caller, it returns the new value, and the caller assigns this value to its own variable. The corrected version is:

public class IncReturn {
    static int inc(int x) {
        return x + 1;
    }

    public static void main(String[] args) {
        int num = 5;
        num = inc(num);
        System.out.println(num);   // 6
    }
}
6

Pass by value applies here too: x is a copy of num, and it is not the method that changes num in main. The change is made by main itself, with the assignment num = inc(num);. This form shows clearly what is happening: the reader can tell from the assignment that num changes on this line. That a method cannot secretly change the caller's variables may look like a restriction, but it is a guarantee that makes programs understandable. That a call such as calc(x) will not spoil x is known without looking at the body of the method.

9.7Overloading

The area of a square is computed with a single side, the area of a rectangle with two. The two jobs could be given separate names such as squareArea and rectangleArea. But both really compute “area”. Java allows methods that do the same job with different inputs to share the same name.

9.7.1Same name, different parameter list

Definition 9.8

Method overloading is defining several methods with the same name in the same class. The parameter lists of these methods must differ: in the number of parameters, the parameter types, or the order of the types. In short, their signatures must differ. The compiler binds a call to one of these methods by looking at the number and types of the arguments.

static int area(int side) {
    return side * side;
}
static int area(int w, int h) {
    return w * h;
}
// ERROR: only the return type differs
static double area(int side) { … }

The first two methods are valid overloading. area(int side) takes one parameter and area(int w, int h) takes two; their signatures are area(int) and area(int, int). The third method is wrong: its parameter list is the same as the first one's, and only the return type differs.

public class Area {
    static int area(int side) {
        return side * side;
    }

    static int area(int w, int h) {
        return w * h;
    }

    public static void main(String[] args) {
        System.out.println(area(4));
        System.out.println(area(3, 5));
    }
}
16
15
area(4)1 int argumentarea(int side)16area(3, 5)2 int argumentsarea(int w, int h)15The compiler looks at the number and types of the arguments; it does not look at the return type.
Figure 9.12: In area(4) there is a single int argument and the one-parameter version is chosen (16). In area(3, 5) there are two int arguments and the two-parameter version is chosen (15). The compiler looks at the number and types of the arguments; it does not look at the return type.

The most familiar example of overloading is System.out.println. The calls println(5), println(2.5), println("Hello") and println(true) each go to a separate method: println(int), println(double), println(String) and println(boolean). The programmer does not have to memorize a separate name for each type. Math.abs and Math.max are also overloaded for int, long, float and double.

9.7.2Which method does the compiler choose?

The choice among overloaded methods is made at compile time, before the program runs. The compiler knows the type of every argument in the call and looks for the signature that fits these types. The program below shows this decision for two calls:

static int area(int side) {
    return side * side;
}
static int area(int w, int h) {
    return w * h;
}
System.out.println(area(4));      // main
System.out.println(area(3, 5));   // main
area(4)call (arguments)area(int)✓ matchesarea(int, int)✗ wants 2 parameterssignatures the compiler sees area(3, 5)call (arguments)area(int)✗ wants 1 parameterarea(int, int)✓ matchessignatures the compiler sees
Figure 9.13: The compiler's choice. (a) area(4): area(int) matches; area(int, int) wants two parameters. (b) area(3, 5): area(int) wants one parameter; area(int, int) matches.

In the call area(4) there is a single int argument. area(int) fits exactly in number and type; area(int, int) is eliminated because it wants two arguments. At run time area(int) is called, side = 4 and 4 × 4 = 16 is returned. In the call area(3, 5) there are two int arguments, and this time only area(int, int) fits: w = 3, h = 5 and 3 × 5 = 15 is returned.

When the type of an argument fits no parameter exactly, the compiler tries widening conversions. A type can be converted to a wider type without losing information: char → int → long → float → double. The compiler first looks for an exactly matching signature. If it finds none, it widens the argument, looks at the signatures that fit, and chooses the one that needs the closest widening. Narrowing, on the other hand, is never done automatically. In the program below a double version has been added to area:

public class AreaDouble {
    static int area(int side) {
        return side * side;
    }

    static int area(int w, int h) {
        return w * h;
    }

    static double area(double side) {
        return side * side;
    }

    public static void main(String[] args) {
        System.out.println(area(4));      // area(int)
        System.out.println(area(2.5));    // area(double)
        System.out.println(area(3, 5));   // area(int, int)
        System.out.println(area(4L));     // long → double: area(double)
        System.out.println(area('B'));    // char → int: area(int)
    }
}
16
6.25
15
16.0
4356
Table 9.9: The compiler's choice for the calls in the AreaDouble program.
CallArgument typesMethod chosenWhy?Result
area(4)intarea(int)exact match16
area(2.5)doublearea(double)exact match6.25
area(3, 5)int, intarea(int, int)exact match15
area(4L)longarea(double)long cannot be narrowed to int; it widens to double16.0
area('B')chararea(int)char → int is the closest widening; 'B' = 664356

The last two lines need attention. 4L is a constant of type long. It cannot be given to area(int), because going from long to int is a narrowing. Since long can widen to double, area(double) is chosen and the result is printed as 16.0, with a decimal point. 'B' is a char. It can widen to both int and double; the compiler chooses the closer one, int. The code of the character 'B' is 66, and 66 × 66 = 4356 is printed. The choice is made entirely at compile time; the value of the argument is not looked at while the program runs.

9.7.3Faulty overloading

The third method above, static double area(int side), has the same signature as the first one: area(int). Only the return type differs. The compiler does not accept this:

public class AreaDuplicate {
    static int area(int side) {
        return side * side;
    }
    static double area(int side) {
        return side * side;
    }
}
AreaDuplicate.java:5: error: method area(int) is already defined in class AreaDuplicate
    static double area(int side) {
                  ^
1 error

The message says “the method area(int) is already defined in this class”. The reason the return type is not part of the signature is clearly visible here. A compiler meeting a call such as area(4); whose result is not used would not know which version was meant. The situation is the same in the call System.out.println(area(4));, because println accepts both int and double. The form of a call consists only of the name and the arguments, and the choice can be based only on these.

If there is no matching signature at all, compilation fails again. The call area(2.5) does not compile when only area(int) and area(int, int) are defined:

public class AreaError {
    static int area(int side) {
        return side * side;
    }
    static int area(int w, int h) {
        return w * h;
    }
    public static void main(String[] args) {
        System.out.println(area(2.5));
    }
}
AreaError.java:9: error: incompatible types: possible lossy conversion from double to int
        System.out.println(area(2.5));
                                ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

In this case JDK 21 gives a shortened message. Because the only one-parameter candidate is area(int), it reports the problem directly as a narrowing from double to int. The note below the message says that the detailed output can be obtained with the -Xdiags:verbose option. With this option the compiler says “no suitable method found for area(double)” and lists separately why each of the two candidates does not fit: a lossy conversion in one, a difference in the number of arguments in the other.

A third kind of error is ambiguity. If two different signatures fit equally well through widening, the compiler cannot make a choice:

public class AmbiguousCall {
    static void f(int a, double b) { }
    static void f(double a, int b) { }
    public static void main(String[] args) {
        f(1, 2);
    }
}
AmbiguousCall.java:5: error: reference to f is ambiguous
        f(1, 2);
        ^
  both method f(int,double) in AmbiguousCall and method f(double,int) in AmbiguousCall match
1 error

In the call f(1, 2) both arguments are int. For f(int, double) the second argument must be widened, and for f(double, int) the first. Both options need one widening and neither is better than the other. The compiler says “reference to f is ambiguous” and shows both candidates. If one of the arguments is written explicitly as a double, the ambiguity disappears:

public class Ambiguous {
    static void f(int a, double b) {
        System.out.println("f(int, double)");
    }

    static void f(double a, int b) {
        System.out.println("f(double, int)");
    }

    public static void main(String[] args) {
        f(1, 2.0);
        f(1.0, 2);
    }
}
f(int, double)
f(double, int)

9.8Variable-length arguments

A method that adds two numbers, another that adds three numbers, a third that adds four… With overloading this road goes on forever. Java offers a syntax that lets a method take as many arguments as wanted.

9.8.1The int... syntax and its rules

Definition 9.9

Variable-length arguments (varargs) are a parameter declared by writing three dots after the parameter type, which accepts zero or more arguments: int... s. The compiler packs the values in the call into an array; inside the method s is an int[] array.

static int add(int... s) {
    int t = 0;
    for (int v : s) t += v;
    return t;
}
add(1, 2, 3)   // 6
add()          // 0
add(new int[]{4, 5})   // 9

Inside the method, s is used like an ordinary array. s.length gives how many arguments arrived. The enhanced for loop for (int v : s) puts the elements of the array into v in turn; one element is processed per iteration. The complete program and its output:

public class Varargs {
    static int add(int... s) {
        int t = 0;
        for (int v : s) t += v;
        return t;
    }

    public static void main(String[] args) {
        System.out.println(add(1, 2, 3));
        System.out.println(add());
        System.out.println(add(new int[]{4, 5}));
        System.out.println(add(10));
    }
}
6
0
9
10

For add(1, 2, 3) the compiler itself creates the array new int[]{1, 2, 3} and passes it to the method. In the call add() there are no arguments; this time the compiler passes an empty array, and the result is 0. In the third call the array is given directly: a varargs parameter also accepts an array, and the result is 4 + 5 = 9. add(10) with a single argument is also valid and returns 10.

A varargs parameter has two rules. It must be at the very end of the parameter list, because that is the only way the compiler can tell which of the values in the call go into the array. And there can be only one in a method. Both rules are enforced with the same compiler message:

public class VarargsLast {
    static int add(int... s, int x) {
        return x;
    }
}
VarargsLast.java:2: error: varargs parameter must be the last parameter
    static int add(int... s, int x) {
                        ^
1 error

The same message appears when two varargs parameters are written (int... s, int... t), because the first is not at the end. Ordinary parameters may come before a varargs parameter. The method below takes a title first and then as many grades as wanted:

public class Label {
    static void show(String title, int... grades) {
        System.out.print(title + ":");
        for (int g : grades) System.out.print(" " + g);
        System.out.println(" (count: " + grades.length + ")");
    }

    public static void main(String[] args) {
        show("Ali", 70, 85, 90);
        show("Ayşe", 100);
        show("Can");
        System.out.printf("%d + %d = %d%n", 2, 3, 2 + 3);
    }
}
Ali: 70 85 90 (count: 3)
Ayşe: 100 (count: 1)
Can: (count: 0)
2 + 3 = 5

No grades were given for “Can”; the array is empty, the loop does not run and grades.length is 0. The printf on the last line of the program is a method in the Java library that uses varargs: its signature is printf(String, Object...). That is why it can take as many values as wanted after the format string.

9.8.2add(1, 2, 3) step by step

In the main below, add is called twice:

static int add(int... s) {
    int t = 0;
    for (int v : s) t += v;
    return t;
}
// in main:
System.out.println(add(1, 2, 3));
System.out.println(add());

The trace of the first call was obtained by running a version in which lines printing the variables on each iteration were added to the method. Table 9.10 was built from this output.

Table 9.10: The iterations of the enhanced for loop in the call add(1, 2, 3).
IterationvOperationt
entry—s = {1, 2, 3}, s.length = 30
Iteration 110 + 1 = 11
Iteration 221 + 2 = 33
Iteration 333 + 3 = 66

At the moment of the call, the array prepared by the compiler is passed to the parameter s: s = {1, 2, 3} and s.length = 3. int t = 0; opens a local box for the sum. The enhanced for sets v = 1 in iteration 1 and t = 0 + 1 = 1. In iteration 2, v = 2 and t = 1 + 2 = 3; in iteration 3, v = 3 and t = 3 + 3 = 6. Since there are no more elements in the array, the loop ends. return t; returns 6. Because the variable v was declared inside the loop, it has gone out of scope with the loop. The frame of add (s and t) is deleted and main prints 6.

main()add(1, 2, 3)adds123t6v3
Figure 9.14: The end of iteration 3: in the frame of add, the array s is {1, 2, 3}, t = 6 and v = 3.

9.8.3The empty call

The second call is add() and contains no arguments. The compiler passes not null but an empty array (new int[0]); s.length = 0. t = 0 is assigned. Because there are no elements in the array, the body of the enhanced for does not run even once and t stays 0. The method returns 0 and the program prints 0.

main()add()adds[ ] emptyt0
Figure 9.15: In the call add(), s is an empty array. The loop body never runs and t stays 0.

Note that the empty call is not an error and that the result is 0. 0 is the identity element of addition: adding 0 to a number does not change it. This is why a sum of no numbers being 0 is natural in mathematics too. By the same logic, in a varargs method that computes a product, the accumulator starts at 1 and the empty call returns 1. By contrast, computations such as “largest element” or “average” have no meaningful answer for empty input. In such methods the empty array must be handled separately at the start. For an integer average, for example, the division 0 / 0 causes an ArithmeticException while the program runs.

9.9Scope

A variable cannot be used from everywhere it is declared. Java gives each variable the right to be visible in a particular region of the program. The boundaries of this region are drawn by curly braces.

9.9.1Local variables and scope

Definition 9.10

Scope is the region of the program in which a variable can be used by its name. Variables declared inside a method, and the parameters of the method, are called local variables. The scope of a local variable starts at the line where it is declared and ends at the closing curly brace of the block in which it is declared. The scope of parameters is the whole body of the method.

Scope has four rules:

  • Parameters and variables declared inside a method are local.
  • A variable declared in a block, that is, between a pair of curly braces { }, is visible only in that block and in the blocks inside it.
  • Two local variables with the same name cannot be declared in the same scope.
  • A method cannot reach a local variable of another method.
calc(int n) { … } — method scopen3sum0if (n > 0) { … } — block scopepart6
Figure 9.16: Nested scopes. The outer box is the method scope of calc: n and sum live here. The dashed inner box is the scope of the if block: part exists only here.

The last rule is understood on its own when thought about together with the call stack. The local variables of a method sit in that method's frame. Another method, either when that frame does not yet exist or while it is running inside another frame, cannot reach that variable. The compiler rejects this access from the start:

public class OtherMethod {
    static void first() {
        int hidden = 42;
    }
    static void second() {
        System.out.println(hidden);
    }
}
OtherMethod.java:6: error: cannot find symbol
        System.out.println(hidden);
                           ^
  symbol:   variable hidden
  location: class OtherMethod
1 error

The message says “cannot find symbol” and states that the symbol sought is a variable named hidden. Inside the method second there is nothing known by this name. The way to carry the value from first to second is for first to return the value and for the caller to give this value to second as an argument.

9.9.2calc(3) step by step

The calc method contains two nested scopes: the method's own scope and the scope of the if block.

static int calc(int n) {
    int sum = 0;
    if (n > 0) {
        int part = n * 2;
        sum += part;
    }
    return sum;
}
System.out.println(calc(3));  // main
Table 9.11: The trace table of the call calc(3). part exists only in steps 5 and 6.
StepLineCall stack (top first)Variables (top frame)Output
19main()——
21calc(3) ← main()n=3—
32calc(3) ← main()n=3, sum=0—
43calc(3) ← main()n=3, sum=0—
54calc(3) ← main()n=3, sum=0, part=6—
65calc(3) ← main()n=3, sum=6, part=6—
76calc(3) ← main()n=3, sum=6—
87calc(3) ← main()n=3, sum=6—
99main()—6

main calls calc(3) and the method scope opens: n = 3. On line 2, sum is declared. Because it is declared in the outermost block of the method, it is visible to the end of the method. On line 3, 3 > 0 is true and the if block is entered; a new inner scope opens here. On line 4, part is declared and gets the value 3 × 2 = 6. This variable exists only inside the if block. On line 5, the inner block reaches sum in the outer scope: sum = 0 + 6 = 6. The inner block sees the outer variables; the reverse is not true. On line 6 the block closes and part disappears. On line 7, return sum; returns 6 and the method scope closes too. The returned 6 becomes the argument to println and is printed.

calc(int n) { … } — method scopen3sum6if (n > 0) { … } — block scopepart6 calc(int n) { … } — method scopen3sum6if (n > 0) { … } — block scopepart → block ended, variable gone
Figure 9.17: (a) After line 5: in the inner block part = 6, in the outer scope sum = 6. (b) After the block closes: part no longer exists; n and sum remain.

Calling the method with a negative number never opens the if block: for calc(-2), part is never created and 0 is returned.

public class Calc {
    static int calc(int n) {
        int sum = 0;
        if (n > 0) {
            int part = n * 2;
            sum += part;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(calc(3));
        System.out.println(calc(-2));
    }
}
6
0

Trying to use part after the block has closed is a compile error. The version below tries to add part as well on the return line:

public class PartOutside {
    static int calc(int n) {
        int sum = 0;
        if (n > 0) {
            int part = n * 2;
            sum += part;
        }
        return sum + part;
    }
}
PartOutside.java:8: error: cannot find symbol
        return sum + part;
                     ^
  symbol:   variable part
  location: class PartOutside
1 error

The compiler does not recognize part on line 8. This line is outside the if block, and there is no variable with this name there. From the compiler's point of view, the situation is no different from the variable never having been declared. If the variable is needed after the block too, its declaration is moved before the block, into the outer scope.

9.9.3Local variables with the same name

Since an inner block sees the variables of the outer scope, what happens if a new variable with the same name is declared in the inner block? In Java this is an error:

public class SameName {
    public static void main(String[] args) {
        int x = 1;
        if (x > 0) {
            int x = 5;   // error
        }
    }
}
SameName.java:5: error: variable x is already defined in method main(String[])
            int x = 5;   // error
                ^
1 error
main method scopex1outer x: visible in the inner block tooif (x > 0) { … } blockint x = 5;✗ x is already defined
Figure 9.18: The x = 1 in the scope of main is visible in the inner if block as well. Declaring int x = 5; in the inner block is an error: x is already defined.

The message says “variable x is already defined in method main(String[])”. In some languages a new variable in an inner block temporarily hides the outer one. Java deliberately forbids this among local variables: if two x's were visible at once, the reader could be confused about which x a line refers to.

Parameters are also local variables and live in the outermost scope of the method. So a variable with the same name as a parameter cannot be declared in the method body:

public class ParamSameName {
    static int add(int a, int b) {
        int a = 3;
        return a + b;
    }
}
ParamSameName.java:3: error: variable a is already defined in method add(int,int)
        int a = 3;
            ^
1 error

In the message the signature of the method appears with the parameter types: add(int,int). Assigning a new value to a parameter (a = 3;) is valid; the error comes only from rewriting the type, that is, from redeclaring it.

The same name can be used again after the scope of a variable has ended. When the block closes, the variable inside it is deleted and the name becomes free:

public class AfterBlock {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.print(i + " ");
        }
        int i = 7;                 // the scope of the earlier i has ended
        System.out.println(i);
        {
            int k = 1;
            System.out.println(k);
        }
        {
            int k = 2;             // a separate block, a separate k
            System.out.println(k);
        }
    }
}
0 1 2 7
1
2

The scope of the i declared in the for header is limited to the loop. When the loop ends, int i = 7; can be written. The two k's declared in two separate blocks do not see each other either; each disappears when its own block ends. If the scopes of two variables with the same name do not overlap, there is no conflict.

9.9.4Shadowing: a static field and a local variable

Variables are not declared only inside methods. A variable can also be declared inside the class but outside all the methods. Such a variable is called a field. A static field belongs to the class, is seen by all the methods of the class and lives for the whole program. Unlike local variables, it is not deleted at the end of a call.

Definition 9.11

Shadowing is declaring, inside a method, a local variable with the same name as a field of the class. Within the scope of the local variable, this name refers to the local variable; the field is left in the shade and does not change. The field can still be reached by writing ClassName.fieldName.

public class FieldShadow {
    static int counter = 100;          // static field

    static void test() {
        int counter = 1;               // the local variable shadows the field
        counter += 5;
        System.out.println("local counter = " + counter);
        System.out.println("field counter = " + FieldShadow.counter);
    }

    public static void main(String[] args) {
        test();
        System.out.println("main: " + counter);
    }
}
local counter = 6
field counter = 100
main: 100

In the method test, the moment int counter = 1; is written, a local counter is born. From then on, inside the method, the name counter refers to this local variable. counter += 5; makes the local variable 6. The value of the field stays at 100; the notation FieldShadow.counter reaches the field itself and 100 is printed. When test ends, the local counter is deleted and the name counter in main again refers to the field: 100.

Shadowing compiling does not contradict the ban among local variables. The ban prevents two local variables from being visible under the same name at the same time. A field and a local variable, however, are of different kinds, and the field can always be told apart by the class name. Even so, shadowing is often the result of carelessness. The programmer thinks they are changing the field but changes a local copy, and the mistake goes unnoticed for a long time. Giving different names to fields and local variables is the safest way.

9.9.5Lifetime and initial value of a local variable

Scope says where a variable is visible. There is also the question of when the variable exists. A local variable is born when its declaration line runs and dies when its block ends. Each time a method is called, its local variables are born anew. No value is remembered from the earlier call. This is why the num in the second call of printPositive knows nothing about the −3 of the first call.

A counter that has to carry a value from one call to the next therefore cannot be local; it must be a static field. For example, a counter that counts how many times a method has been called, if declared inside the method as int counter = 0;, starts from 0 at every call and can never go beyond 1.

There is one more difference between fields and local variables. A static int field starts at 0 by itself if no value is given. A local variable has no initial value of its own. The compiler does not allow a local variable that has not been given a value to be read:

public class NoInitialValue {
    static int sumTo(int n) {
        int t;
        for (int i = 1; i <= n; i++) t += i;
        return t;
    }
}
NoInitialValue.java:4: error: variable t might not have been initialized
        for (int i = 1; i <= n; i++) t += i;
                                     ^
NoInitialValue.java:5: error: variable t might not have been initialized
        return t;
               ^
2 errors

The message says “variable t might not have been initialized”. The error is reported on two lines: t += i reads the old value of t, and return t reads it too. The fix is to start the accumulator with int t = 0;. The accumulator starts at 0 for addition and at 1 for multiplication.

9.10Built-in methods: Math

Java's library contains thousands of ready-made methods. One of the most frequently used is the Math class. The methods of Math are static; they are called with the class name without creating an object: Math.sqrt(16). Like the methods written in these notes, they take parameters and return values, and many of them are overloaded.

Table 9.12: Frequently used Math methods (the results are JDK 21 output).
CallResultReturn typeNote
Math.abs(-7)7intabsolute value; overloaded for int, long, float, double
Math.abs(-7.5)7.5doublewhen the argument is double, the double version is chosen
Math.max(3, 9)9intreturns the larger
Math.max(3, 9.5)9.5double3 widens to double, and max(double, double) is chosen
Math.min(-4, 2)-4intreturns the smaller
Math.sqrt(16)4.0doublesquare root; the result is always double
Math.sqrt(-1)NaNdoublea negative number has no real square root: “not a number”
Math.pow(2, 10)1024.0doubleexponentiation; assigning to an int needs (int)
Math.round(2.5)3longrounds to the nearest integer
Math.round(2.4)2longrounds down
Math.round(-2.5)-2longexactly at the half, rounds to the larger, that is, to −2
public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-7));
        System.out.println(Math.max(3, 9));
        System.out.println(Math.sqrt(16));
        System.out.println(Math.pow(2, 10));
        System.out.println(Math.round(2.5));
        System.out.println(Math.sqrt(-1));
        System.out.println(Math.abs(-7.5));
        System.out.println(Math.max(3, 9.5));
        System.out.println(Math.round(-2.5));
        System.out.println(Math.round(2.4));
        int p = (int) Math.pow(2, 10);
        System.out.println(p);
        System.out.println(Math.abs(Integer.MIN_VALUE));
        System.out.println(Math.min(-4, 2));
    }
}
7
9
4.0
1024.0
3
NaN
7.5
9.5
-2
2
1024
-2147483648
-4

The decimal point in the numbers 4.0 and 1024.0 in the output comes from the return type being double. Even though the result of Math.sqrt(16) is a whole number in mathematics, the method always returns double. When using a method, the type of the result matters as much as its value. The result of a method whose return type is double or long cannot be assigned directly to an int variable:

public class PowInt {
    public static void main(String[] args) {
        int p = Math.pow(2, 10);
    }
}
PowInt.java:3: error: incompatible types: possible lossy conversion from double to int
        int p = Math.pow(2, 10);
                        ^
1 error
public class RoundInt {
    public static void main(String[] args) {
        int r = Math.round(2.5);
    }
}
RoundInt.java:3: error: incompatible types: possible lossy conversion from long to int
        int r = Math.round(2.5);
                          ^
1 error

Both errors are narrowing errors. Math.pow returns double, and Math.round(double) returns long. If the programmer is sure the result will fit in an int, they write an explicit cast: int p = (int) Math.pow(2, 10); compiles and gives 1024.

It may be surprising that Math.round(-2.5) gives −2, not −3. Math.round behaves as if it adds 0.5 to the number and takes the floor of the result: −2.5 + 0.5 = −2. Numbers exactly at the half are always rounded toward the larger value, that is, toward positive infinity: 2.5 → 3 and −2.5 → −2. Likewise, the result of the call Math.abs(Integer.MIN_VALUE) is negative (−2147483648). 2147483648, the absolute value of the smallest int value, is one more than the largest int value (2147483647) and does not fit in an int. This is why the method that finds the digit count first converts the number to long.

Before using a built-in method, read its documentation for the parameters, the return type and the special cases. That Math.sqrt(-1) returns NaN instead of throwing an error, or that Math.round returns long, can be learned only by looking at the documentation.

9.11Method design

A method that compiles and gives the correct result is not always a good method. A hundred-line method that does five jobs at once and both prints its result to the screen and stores it in a field may work, but it is hard to read, test and change. What separates a good method from a bad one is how it is divided and how it is named.

9.11.1Abstraction

Definition 9.12

Abstraction is hiding the details of a task and offering only a name and an interface that show what the task does. The abstraction of a method is its signature and its contract: what it takes, what it returns and under what conditions it works correctly.

calling codeMath.sqrt(16)visible: signature + contractdouble sqrt(double x)√x for x ≥ 0hidden: body? ? ?may change
Figure 9.19: Abstraction. The calling code only writes Math.sqrt(16). The visible part is the signature (double sqrt(double x)) and the contract (√x for x ≥ 0). The body is hidden and may change.

A method hides the implementation detail from the calling code. A well-named method says what is done; how it is done stays in the body. A student using Math.sqrt does not know whether the square root is computed with Newton's method or with a special processor instruction, and does not need to.

Abstraction has an important benefit: even if the body changes, callers are not affected as long as the signature stays the same. Suppose a prime-number method was first written with a slow loop that tries all divisors from 2 to n − 1. Later it is replaced with a fast version that looks only up to √n. None of the hundred lines that call isPrime(n) changes; all of them get faster on their own.

9.11.2Decomposition

A big task is divided into subtasks, each with a single responsibility. For each subtask the input, the output and what happens on bad input must be determined. The top-level method combines these subtasks in a meaningful order. A top-level method written this way reads like a table of contents. This approach is called decomposition.

gradeReport()readGrades()inputcomputeAverage()computation, pureletterGrade(avg)decisionwriteReport(…)output
Figure 9.20: Decomposing the grade-report task. gradeReport() calls four submethods: one that reads the grades (input), one that computes the average (computation, pure), one that determines the letter grade (decision) and one that writes the report (output).

The following program applies the decomposition in the figure to a small example. Because the reading job is short, it has not been made a separate method; it is written in the first three lines of gradeReport. The letter-grade boundaries have been chosen as an example.

import java.util.Scanner;

public class GradeReport {
    static double computeAverage(int a, int b, int c) {
        return (a + b + c) / 3.0;
    }

    static String letterGrade(double avg) {
        if (avg >= 85) return "AA";
        if (avg >= 70) return "BB";
        if (avg >= 60) return "CC";
        if (avg >= 50) return "DD";
        return "FF";
    }

    static void writeReport(double avg, String letter) {
        System.out.println("Average: " + Math.round(avg * 100) / 100.0);
        System.out.println("Letter grade: " + letter);
    }

    static void gradeReport(Scanner input) {
        int g1 = input.nextInt();               // read the grades
        int g2 = input.nextInt();
        int g3 = input.nextInt();
        double avg = computeAverage(g1, g2, g3);
        writeReport(avg, letterGrade(avg));
    }

    public static void main(String[] args) {
        gradeReport(new Scanner(System.in));
    }
}

Outputs for three different inputs:

Table 9.13: The output of the GradeReport program for three inputs.
InputAverage (computation)Output
70 85 91246 / 3 = 82
Average: 82.0
Letter grade: BB
50 60 71181 / 3 ≈ 60,33
Average: 60.33
Letter grade: CC
40 45 52137 / 3 ≈ 45,67
Average: 45.67
Letter grade: FF

Each method has a single job, and each can be tried separately. computeAverage only computes. Note that the division is done by 3.0: if (a + b + c) / 3 were written, integer division between two ints would be done, and for 181 / 3 the result would be 60 instead of 60.33. The return type being double does not by itself make this division fractional; the conversion happens after the division is finished. letterGrade only makes a decision; because it is written with successive early returns, each threshold is one line. writeReport is concerned only with output. To round the average to two decimal places, Math.round(avg * 100) / 100.0 is used: 60.333… × 100 = 6033.3… → 6033 → 60.33. If the letter-grade boundaries change, only letterGrade changes; if the format of the report changes, only writeReport changes.

9.11.3Principles of good method design

Whether a method is well designed can be tested with a few questions:

Table 9.14: The principles of good method design and the question for each principle.
PrincipleQuestionBad example → good example
Single taskCan the method be described in one sentence?a process() that reads, computes and writes → readGrades, computeAverage, writeReport
Meaningful nameDoes the name tell the result or the action?f(x), op2() → digitCount(x), isEven(x)
Few parametersAre all the inputs necessary?an unused int mod parameter → remove the parameter
Clear resultAre the return and the side effects clear?a method that both prints and returns → a method that only returns
TestabilityCan the method be tried with independent examples?a computing method that reads from the keyboard → a method that takes the value as a parameter

These principles support one another. It is easy to give a meaningful name to a single-task method. A method with few parameters that returns its result is easy to test. There is no exact limit on length. Even so, a method that exceeds a screen in height is a candidate for splitting. If its body has sections that separate with “now do this”, each of these sections should probably be a separate method.

9.12Example methods

The examples below bring together the concepts about methods on small, familiar problems. Each method is first written, then executed step by step with the call stack or a trace table.

9.12.1The contract first

Before a method is written, what it will do must be stated clearly. The name of the method should say what it does, the valid range of the parameters should be defined, and the meaning of the return value and what happens on bad input should be known. The sum of this information is called the method's contract.

Definition 9.13

A contract is the agreement between a method and its caller. A precondition is a condition the caller must satisfy (e.g. “n ≥ 0”). A postcondition is the result the method guarantees when the precondition is satisfied (e.g. “returns the number of digits of n”).

// Task  : returns the number of decimal digits.
// Input : any int (may be negative).
// Output: 1..10; 1 for 0, 3 for -507.
static int digitCount(int num) { … }
input (precondition)any intmay be negativedigitCountoutput (postcondition)1 … 10returns, does not printexamples:0 → 1-507 → 32147483647 → 10-2147483648 → 10
Figure 9.21: The contract of digitCount. Precondition: any int, possibly negative. Postcondition: returns a number between 1 and 10 and does not print. Examples: 0 → 1, −507 → 3, 2147483647 → 10, −2147483648 → 10.

The examples in the contract are test cases determined before the method is written. They deliberately include boundary values: 0 has one digit but is an input for which the loop will never run; the largest and smallest int values are the longest numbers. After the body is written, all these examples are tried. In a method started without a contract, the question “what should be returned for 0?” is often asked only when a bug appears.

9.12.2Even or odd?

static boolean isEven(int num) {
    return num % 2 == 0;
}

If the remainder is 0 when a number is divided by 2, the number is even. isEven returns the result of this comparison, that is, a boolean value, directly. Writing it as if (num % 2 == 0) return true; else return false; is also correct, but needlessly long: the expression num % 2 == 0 is already true or false.

numnum % 2isEven(num)71false100true-40true-3-1falseIn Java the remainder of a negative number can be negative (-3 % 2 = -1); that is why the test is == 0.
Figure 9.22: isEven for four inputs: 7 % 2 = 1 → false; 10 % 2 = 0 → true; −4 % 2 = 0 → true; −3 % 2 = −1 → false.

The last column of the figure shows an important detail. In Java the remainder of a negative number can be negative: the sign of the remainder follows the sign of the dividend, and −3 % 2 = −1. Writing the odd-number test as num % 2 == 1 is therefore wrong; for −3 it gives false and treats −3 as even. Testing evenness with == 0 works correctly for every sign. The real output of the program gives, on each line, the number, the remainder and the result of the method:

public class IsEven {
    static boolean isEven(int num) {
        return num % 2 == 0;
    }

    public static void main(String[] args) {
        if (isEven(7)) System.out.println("even");
        else System.out.println("odd");
        int[] samples = {7, 10, -4, -3, 0};
        for (int s : samples)
            System.out.println(s + " " + (s % 2) + " " + isEven(s));
    }
}
odd
7 1 false
10 0 true
-4 0 true
-3 -1 false
0 0 true

The method does not print; it returns the result. That is why it is used directly in the if condition. When the call isEven(7) is traced, num = 7 in the frame, 7 % 2 = 1 and, since 1 == 0 is false, false is returned. The return value takes the place of the call: if (false). The then branch is skipped and the else branch prints “odd”. It is the caller, not the method, that has decided what to print. The same isEven can be used unchanged in another program to count even numbers or to filter a list.

9.12.3Digit count

static int digitCount(int num) {
    long rest = Math.abs((long) num);
    if (rest == 0) return 1;
    int count = 0;
    while (rest > 0) {
        count++;
        rest /= 10;
    }
    return count;
}
System.out.println(digitCount(-507));

The method first takes the absolute value of the number, because −507 and 507 have the same number of digits. It then makes the early return for 0. After that, each time the number is divided by 10 it loses one digit; the method counts how many divisions it takes until the number becomes 0. The result is not printed but returned; the caller uses it however it likes.

Table 9.15 gives the iterations of the loop in the call digitCount(-507). Before the loop, rest = |−507| = 507; since 507 == 0 is false, there is no early return and the loop is entered with count = 0.

Table 9.15: The iterations of the while loop in the call digitCount(-507). rest /= 10 is integer division.
IterationCondition rest > 0countrest
Iteration 1507 > 0 → true1507 / 10 = 50
Iteration 250 > 0 → true250 / 10 = 5
Iteration 35 > 0 → true35 / 10 = 0
exit0 > 0 → false3—

In each iteration rest /= 10 drops the last digit of the number: 507 → 50 → 5 → 0. The loop runs three times and 3 is returned. This call was made first to get the argument of the println in main; the returned 3 took the place of the call and println(3) ran.

main()println(digitCount(-507))digitCountnum-507rest507 main()println(digitCount(-507))digitCountnum-507rest0count3closedreturn 3
Figure 9.23: (a) After Math.abs: num = −507, rest = 507. (b) The loop has finished: rest = 0, count = 3; the frame closes with return 3.

All the examples in the contract have actually been tried:

public class DigitCount {
    static int digitCount(int num) {
        long rest = Math.abs((long) num);
        if (rest == 0) return 1;
        int count = 0;
        while (rest > 0) {
            count++;
            rest /= 10;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(digitCount(-507));
        System.out.println(digitCount(0));
        System.out.println(digitCount(9));
        System.out.println(digitCount(10));
        System.out.println(digitCount(2147483647));
        System.out.println(digitCount(-2147483648));
    }
}
3
1
1
2
10
10

The (long) cast in the first line also has a reason. The absolute value of −2147483648, the smallest int value, does not fit in an int, and Math.abs again returns −2147483648 for this number. A version written without the cast therefore gives a wrong result:

public class DigitWrong {
    static int digitCount(int num) {
        int rest = Math.abs(num);      // without converting to long
        if (rest == 0) return 1;
        int count = 0;
        while (rest > 0) {
            count++;
            rest /= 10;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(Math.abs(-2147483648));
        System.out.println(digitCount(-2147483648));
        System.out.println(digitCount(-507));
    }
}
-2147483648
0
3

In the faulty version, rest stays negative. Because it is not equal to 0, there is no early return. Because the condition rest > 0 is false the first time, the loop never runs and 0 is returned. Yet the contract said “between 1 and 10”. The correct version first converts the number to long. In a long, 2147483648 is easily represented, and the long version of Math.abs gives the right result. This is a bug that shows up only when tried with a boundary value, and it shows the value of writing boundary values into the contract.

9.12.4Is it prime?

A number greater than 1 that has no divisors other than itself and 1 is called a prime number. To find out whether a number is prime, the possible divisors are tried in order. The moment a divisor is found, the answer is settled and the method makes an early return.

static boolean isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i <= n / i; i++)
        if (n % i == 0) return false;
    return true;
}

The expression i <= n / i in the loop condition may look strange at first. This condition makes i be tried up to the square root of n. The reason is this: if n can be written as the product of two numbers, that is, n = p × q, then at least one of p and q cannot be greater than √n. If both were greater than √n, their product would exceed n. So if n has a divisor greater than √n, it also has a partner smaller than √n, and that partner would already have been tried. For example, 91 = 7 × 13 and √91 ≈ 9.54. There is no need to wait for 13; the divisor is found when 7 is tried.

The condition i <= n / i is the form of the condition i * i <= n written with integer division. This form prevents the product i * i from exceeding the int limit when n is very large. Table 9.16 shows how the condition works for 37. The values in the table were obtained by running a version of the loop with a print line added, on JDK 21.

Table 9.16: isPrime(37): only the values of i with i ≤ n / i are tried (√37 ≈ 6.08).
in / iCondition i <= n / in % iDoes it divide?
237 / 2 = 182 ≤ 18 → true37 % 2 = 1no
337 / 3 = 123 ≤ 12 → true37 % 3 = 1no
437 / 4 = 94 ≤ 9 → true37 % 4 = 1no
537 / 5 = 75 ≤ 7 → true37 % 5 = 2no
637 / 6 = 66 ≤ 6 → true37 % 6 = 1no
737 / 7 = 57 ≤ 5 → false—the loop ends: return true

Five values, i = 2 to 6, are tried and none divides 37. At i = 7, 37 / 7 = 5 and 7 ≤ 5 is false; the loop ends and the method returns true. A simple version that tries all the numbers from 2 to 36 would compute 35 remainders; this version computes only 5. The result is the same. For a number that is not prime, the loop ends at the first divisor. For 49 = 7 × 7, at i = 7, 7 ≤ 49 / 7 = 7 is true and 49 % 7 = 0 is found:

Table 9.17: isPrime(49): the condition is still true for i = 7, because 7 × 7 = 49.
in / iCondition i <= n / in % iDoes it divide?
249 / 2 = 242 ≤ 24 → true49 % 2 = 1no
349 / 3 = 163 ≤ 16 → true49 % 3 = 1no
449 / 4 = 124 ≤ 12 → true49 % 4 = 1no
549 / 5 = 95 ≤ 9 → true49 % 5 = 4no
649 / 6 = 86 ≤ 8 → true49 % 6 = 1no
749 / 7 = 77 ≤ 7 → true49 % 7 = 0yes: return false

This example shows why <=, not <, is used in the condition. If i < n / i were written, 7 would never be tried and 49 would be taken for a prime. Perfect squares are good test inputs for catching this kind of boundary error.

The method can be traced for 15 and 7. In isPrime(15), for n = 15, first 15 < 2 is false. For i = 2, 2 ≤ 15 / 2 = 7 is true but 15 % 2 = 1; i increases. For i = 3, 3 ≤ 15 / 3 = 5 is true and 15 % 3 = 0: return false runs and the remaining iterations never run. In isPrime(7), for i = 2, 2 ≤ 7 / 2 = 3 is true and 7 % 2 = 1. For i = 3, 3 ≤ 7 / 3 = 2 is false: no divisor has been found up to √7, the loop ends without an early return and true is returned.

public class IsPrime {
    static boolean isPrime(int n) {
        if (n < 2) return false;
        for (int i = 2; i <= n / i; i++)
            if (n % i == 0) return false;
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPrime(15));
        System.out.println(isPrime(7));
        System.out.println(isPrime(37));
        System.out.println(isPrime(1) + " " + isPrime(2) + " " + isPrime(4) + " " + isPrime(49) + " " + isPrime(97));
        for (int k = 1; k <= 30; k++)
            if (isPrime(k)) System.out.print(k + " ");
        System.out.println();
    }
}
false
true
true
false true false false true
2 3 5 7 11 13 17 19 23 29 

The last line shows the primes obtained by calling the method in a loop with the numbers from 1 to 30. Note that isPrime(1) returns false and isPrime(2) returns true. 1 is not prime and is eliminated by the early return in the first line. For 2, the loop condition 2 ≤ 2 / 2 = 1 is false from the start; the loop never runs and true is returned.

9.12.5GCD: Euclid's algorithm

The greatest common divisor (GCD) of two numbers is the largest number that divides both without a remainder. Instead of trying all the numbers from 1 up to the smaller number, the roughly 2,300-year-old Euclid's algorithm offers a much faster way: gcd(a, b) = gcd(b, a % b), and when b = 0 the answer is a.

static int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return Math.abs(a);
}
System.out.println(gcd(48, 18));  // main

The correctness of the algorithm rests on this observation: every number that divides both a and b also divides the difference a % b = a − k × b. Conversely, every number that divides both b and a % b also divides a. So the pair (a, b) and the pair (b, a % b) have the same common divisors, and therefore the same GCD. The numbers get smaller in each iteration. Finally b = 0 and gcd(a, 0) = a, because every number divides 0.

Table 9.18: The iterations of gcd(48, 18) (the values are taken from a trace version run on JDK 21).
Iterationr = a % babCondition b != 0
start—481818 != 0 → true
Iteration 148 % 18 = 12181212 != 0 → true
Iteration 218 % 12 = 61266 != 0 → true
Iteration 312 % 6 = 0600 != 0 → false

At the start a = 48, b = 18 and 18 != 0 is true. In iteration 1, r = 48 % 18 = 12 (48 = 2 × 18 + 12); a = 18, b = 12. This means gcd(48, 18) = gcd(18, 12). In iteration 2, r = 18 % 12 = 6; a = 12, b = 6. In iteration 3, r = 12 % 6 = 0; a = 6, b = 0. The condition 0 != 0 is false and 6 is returned. Check: 48 = 6 × 8, 18 = 6 × 3, and 8 and 3 have no common divisor other than 1. Only three iterations were enough.

main()println(gcd(48, 18))gcda18b12r12 main()println(gcd(48, 18))gcda6b0closedreturn 6
Figure 9.24: (a) The frame of gcd after iteration 1: a = 18, b = 12, r = 12. (b) The loop has finished: a = 6, b = 0; return 6.

If the numbers are given in the reverse order, the first iteration swaps them by itself: since 18 % 48 = 18, gcd(18, 48) reaches the state of gcd(48, 18) after the first iteration. The method also works correctly with 0: gcd(7, 0) never enters the loop and returns 7. The Math.abs in the last line makes the result positive for negative inputs: gcd(-12, 18) returns 6, not −6.

public class Gcd {
    static int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return Math.abs(a);
    }

    static int lcm(int a, int b) {
        if (a == 0 || b == 0) return 0;
        return Math.abs(a / gcd(a, b) * b);
    }

    public static void main(String[] args) {
        System.out.println(gcd(48, 18));
        System.out.println(lcm(12, 18));
        System.out.println(gcd(18, 48) + " " + gcd(17, 5) + " " + gcd(7, 0) + " " + gcd(100, 75));
        System.out.println(lcm(4, 6) + " " + lcm(5, 7) + " " + lcm(8, 12));
    }
}
6
36
6 1 7 25
12 35 24

9.12.6LCM: calling a method from a method

The least common multiple (LCM) of two numbers is easily found with the GCD: lcm(a, b) = a × b / gcd(a, b). Since the method that computes the GCD has already been written, the lcm method calls it; the real computation is a single line:

static int lcm(int a, int b) {
    if (a == 0 || b == 0) return 0;
    return Math.abs(a / gcd(a, b) * b);
}
// gcd: Euclid's algorithm
System.out.println(lcm(12, 18));  // main
Table 9.19: The trace table of the call lcm(12, 18). In steps 3 and 4 there are three frames on the stack.
StepLineCall stack (top first)Variables (top frame)Output
16main()——
21lcm(12, 18) ← main()a=12, b=18—
33gcd(12, 18) ← lcm(12, 18) ← main()a=12, b=18—
43gcd(12, 18) ← lcm(12, 18) ← main()a=6, b=0—
53lcm(12, 18) ← main()a=12, b=18—
63lcm(12, 18) ← main()a=12, b=18—
76main()—36

main calls lcm(12, 18) and the frame of lcm is opened: a = 12, b = 18. Because neither is zero, the early return on line 2 is skipped. To compute the expression in the return line, gcd(a, b) must be called first. There are three frames on the stack. gcd runs its own loop: (12, 18) → (18, 12) → (12, 6) → (6, 0) and returns 6. Although the names are the same, the a and b of gcd are boxes separate from the a and b of lcm. While the a of gcd goes down to 6, the a of lcm stays at 12. 6 takes the place of the call and the expression is computed: 12 / 6 × 18 = 2 × 18 = 36. lcm returns 36 and 36 is printed.

main()println(lcm(12, 18))lcma12b18a / gcd(a, b) * bgcda6b0closedreturn 6
Figure 9.25: gcd is above lcm: the a = 6, b = 0 of gcd is about to return 6; the a = 12, b = 18 of lcm below is unchanged.

There is a reason why the formula in the code is written as a / gcd(a, b) * b instead of a * b / gcd(a, b). Dividing first keeps the intermediate result from growing. The product a × b can be too big to fit in an int. But a is always divisible by the GCD without a remainder, and the quotient is small. The difference between the two forms shows up with large numbers:

public class LcmOverflow {
    static int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return Math.abs(a);
    }

    static int lcmMultiplyFirst(int a, int b) {
        return a * b / gcd(a, b);
    }

    static int lcm(int a, int b) {
        if (a == 0 || b == 0) return 0;
        return Math.abs(a / gcd(a, b) * b);
    }

    public static void main(String[] args) {
        System.out.println(lcmMultiplyFirst(12, 18) + " " + lcm(12, 18));
        System.out.println(lcmMultiplyFirst(100000, 300000) + " " + lcm(100000, 300000));
    }
}
36 36
-647 300000

For 12 and 18 both forms give 36. For 100000 and 300000, however, the product 100000 × 300000 = 30,000,000,000 exceeds the upper limit of int (about 2.1 billion). The overflowed product turns into a meaningless negative number and the result comes out as −647. The form that divides first gives the right answer with 100000 / 100000 × 300000 = 300000. The sneaky thing about this bug is that neither the compiler nor the runtime gives any warning.

The first line of lcm also covers an edge case. If one of the numbers is 0, the common multiple is 0; when both numbers are 0, gcd(0, 0) returns 0, and without the check the division 0 / 0 would throw an ArithmeticException. The outer Math.abs makes the result positive for negative inputs: lcm(-4, 6) gives 12.

Calling a method from within a method avoids code duplication. The loop that computes the GCD has not been written again inside lcm. If a bug is found and fixed in gcd, lcm is fixed automatically too.

9.12.7Reuse: max3

To find the largest of three numbers, there is no need to write a new chain of comparisons. The method that gives the larger of two numbers is used twice: first the larger of the first two numbers is found, then this result is compared with the third number.

static int max(int a, int b) {
    if (a > b) return a;
    return b;
}
static int max3(int a, int b, int c) {
    return max(max(a, b), c);
}
System.out.println(max3(4, 9, 7));  // main
Table 9.20: The trace table of the call max3(4, 9, 7). max is called twice, with two separate frames.
StepLineCall stack (top first)Variables (top frame)Output
18main()——
25max3(4, 9, 7) ← main()a=4, b=9, c=7—
36max3(4, 9, 7) ← main()a=4, b=9, c=7—
41, 2max(4, 9) ← max3(4, 9, 7) ← main()a=4, b=9—
53max(4, 9) ← max3(4, 9, 7) ← main()a=4, b=9—
66max3(4, 9, 7) ← main()a=4, b=9, c=7—
72max(9, 7) ← max3(4, 9, 7) ← main()a=9, b=7—
86max3(4, 9, 7) ← main()a=4, b=9, c=7—
98main()—9

In the frame of max3, a = 4, b = 9, c = 7. The line return max(max(a, b), c); has a nested call, and the inner one is computed first: max(4, 9). In the new frame a = 4, b = 9. Since 4 > 9 is false, the first return is skipped and return b; returns 9. The expression has simplified to max(9, 7). The same method is called a second time, with a brand-new frame: a = 9, b = 7. 9 > 7 is true and return a; returns 9. max3 returns this 9 too, and 9 is printed.

main()println(max3(4, 9, 7))max3a4b9c7max(max(4, 9), 7)maxa4b9 main()println(max3(4, 9, 7))max3a4b9c7max(9, 7)maxa9b7closedreturn 9
Figure 9.26: (a) The inner call: the frame of max(4, 9) is above max3. (b) The outer call: max(9, 7) returns 9.

In this design the comparison logic is in one place. If there is a bug, for example if < was written by mistake instead of >, it is fixed in a single place. The order in which the numbers are given does not change the result; it works correctly with equal and negative numbers too:

public class Max3 {
    static int max(int a, int b) {
        if (a > b) return a;
        return b;
    }

    static int max3(int a, int b, int c) {
        return max(max(a, b), c);
    }

    public static void main(String[] args) {
        System.out.println(max3(4, 9, 7));
        System.out.println(max3(9, 4, 7) + " " + max3(4, 7, 9) + " " + max3(5, 5, 5) + " " + max3(-2, -7, -1));
    }
}
9
9 9 5 -1

9.12.8Methods that return double: temperature conversion

The conversion between Celsius and Fahrenheit is done with the formulas F = C × 9 / 5 + 32 and C = (F − 32) × 5 / 9. Since the results can be fractional, both methods take double and return double.

static double fahrenheit(double c) {
    return c * 9 / 5 + 32;
}
static double celsius(double f) {
    return (f - 32) * 5 / 9;
}
double f = fahrenheit(25);          // main
System.out.println(f);
System.out.println(celsius(f));
Table 9.21: The trace table of the calls fahrenheit(25) and celsius(f).
StepLineCall stack (top first)Variables (top frame)Output
17main()——
21fahrenheit(25.0) ← main()c=25.0—
32fahrenheit(25.0) ← main()c=25.0—
47main()f=77.0—
58main()f=77.077.0
69celsius(77.0) ← main()f=77.077.0
75celsius(77.0) ← main()f=77.077.0
89main()f=77.077.0 / 25.0

In the call fahrenheit(25) the argument is int but the parameter is double. Widening is done automatically and c = 25.0. In the body, 25.0 × 9 = 225.0, 225.0 / 5 = 45.0 and 45.0 + 32 = 77.0 are computed. In main, f = 77.0, and because it is a double it is printed in the form 77.0, with a decimal point. Then celsius(f) is called. The value of f is copied into celsius's own f parameter; again, having the same name creates no link. (77.0 − 32) × 5 / 9 = 45.0 × 5 / 9 = 225.0 / 9 = 25.0 is found and 25.0 is printed. The two methods are inverses of each other. Giving the result of one to the other and getting back to the starting value is an easy way to test the two together.

public class Temperature {
    static double fahrenheit(double c) {
        return c * 9 / 5 + 32;
    }

    static double celsius(double f) {
        return (f - 32) * 5 / 9;
    }

    public static void main(String[] args) {
        double f = fahrenheit(25);
        System.out.println(f);
        System.out.println(celsius(f));
        System.out.println(fahrenheit(100) + " " + fahrenheit(-40) + " " + celsius(98.6));
        System.out.println(5 / 9 * (f - 32));
        System.out.println((f - 32) * 5 / 9);
    }
}
77.0
25.0
212.0 -40.0 37.0
0.0
25.0

The third line checks a few known values: the boiling point of water, 100 °C = 212 °F, −40, where the two scales meet, and human body temperature, 98.6 °F = 37 °C. The fourth line shows a common mistake. If the formula is written as 5 / 9 * (f - 32), 5 / 9 is computed first. Integer division between two ints gives 0, and the result is 0.0 whatever the value of f. In the correct form, (f - 32), a double, is computed first; the following multiplication and division are done in double arithmetic and the right result (25.0) is obtained.

9.12.9Pure methods and side effects

Definition 9.14

A side effect is any change a method leaves in the world apart from returning a value: printing to the screen, changing a field, adding a record to a file. A pure method is a method that always returns the same result for the same inputs and has no side effects.

Two small methods show the difference clearly:

public class PureDemo {
    static int square(int x) {
        return x * x;
    }

    static void printSquare(int x) {
        System.out.println(x * x);
    }

    public static void main(String[] args) {
        int t = square(3) + square(4);
        System.out.println(t);
        printSquare(4);
        System.out.println(square(square(2)));
    }
}
25
16
16

square is pure. square(4) is always 16 and can be used anywhere: inside a sum (9 + 16 = 25), as an argument to another call (square(square(2)) = square(4) = 16) or in a condition. printSquare, however, only prints to the screen. Its result cannot be used in another computation. printSquare(3) + printSquare(4) does not even compile, because printSquare is void.

Pure methods are easier to test. It is enough to check square(4) == 16; there is no need to capture screen output or to remember the earlier value of a field. This is why a computing method and a printing method are kept apart. The computation is done in a pure method, and the printing is left to a separate method or to main. When a side effect is unavoidable, for example when a report really must be written, the side effect is named explicitly and confined: the name writeReport says what it does, and it does nothing else.

Printing to the screen is not the only thing that spoils the purity of a method. A method that changes a static field also has a side effect. The result of a method that increases a counter on every call may vary with how many times it has been called. Methods that read from the keyboard or generate random numbers are also not pure, because they can give different results when called with the same input.

9.13Summary

  • A method is a named group of statements defined inside a class that does a task. It takes its input through parameters and gives its result as a return value. A method is defined once and called wherever you like and as many times as you like.
  • The formal parameters written in the definition are variables; the actual arguments written in the call are values. Arguments are matched to parameters in order; their number and types must fit.
  • In a call, the arguments are evaluated and copied into the parameters, the body runs, return sends the value, and the calling code continues with the value that has taken the place of the call.
  • Each call opens its own frame on top of the call stack. Only the topmost frame runs; when the method ends, its frame is deleted together with all its local variables. The last frame opened is the first to close.
  • The header consists of the access modifier, the modifier, the return type, the name and the parameter list. The signature is the name and the list of parameter types; the return type is not part of the signature.
  • main is static, because the JVM calls it when no object exists. A static method cannot directly call a non-static method.
  • A void method does not return a value; its job is a side effect. A void call cannot be part of an expression. Early return filters out special cases at the start of the method.
  • In a method that is not void, every path must end with a return. The returned value must fit the return type; narrowing is not done automatically.
  • Java always passes arguments by value. Even if a method changes its parameter, the caller's variable does not change; this is why a swap method that swaps primitive variables cannot be written. The new value is returned and the caller assigns it.
  • In overloading, methods with the same name have different parameter lists. The compiler makes the choice at compile time, looking first for an exact match and then for the closest widening. Two methods that differ only in return type, and two equally fitting candidates, are compile errors.
  • Variable-length arguments (int... s) are an array inside the method. The parameter comes at the very end of the parameter list; an empty array is passed in a call with no arguments.
  • Scope is the region in which a variable can be used, and it is bounded by curly braces. Two local variables with the same name cannot be declared in the same scope. A local variable with the same name as a field shadows the field. A local variable cannot be read before it has been given an initial value.
  • Math methods are static and overloaded. sqrt and pow return double, and round(double) returns long.
  • A good method does a single task, has a meaningful name, takes few parameters, returns its result and can be tried with independent examples. Abstraction separates what is done from how it is done; decomposition splits a big task into submethods; a contract states the preconditions and postconditions.
  • A method can call another method (lcm → gcd, max3 → max); each call opens its own frame on the stack. A pure method always gives the same result for the same input and has no side effects; this is why it is easy to test and can be reused everywhere.

9.14Key terms

These are the key terms introduced in this chapter.

  • method
  • method call
  • parameter
  • formal parameter
  • argument
  • actual argument
  • return type
  • return value
  • return
  • method signature
  • static method
  • main method
  • command-line argument
  • stack
  • stack frame
  • call stack
  • code tracing
  • early return
  • side effect
  • pass by value
  • reference
  • method overloading
  • widening conversion
  • narrowing conversion
  • varargs
  • enhanced for loop
  • scope
  • local variable
  • field
  • shadowing
  • compile-time error
  • abstraction
  • decomposition
  • contract
  • reuse
  • pure method
  • integer division
  • overflow
  • identity element
  • greatest common divisor (GCD)
  • least common multiple (LCM)

9.15Test Yourself

  1. The method static double circleArea(double r) { return Math.PI * r * r; } is called in main as double s = circleArea(2 * radius);. What are the parameter, the argument, the return type and the signature in these lines?

    Answer

    The formal parameter is r; it is the variable declared with its type (double r) in the header. The actual argument is the expression 2 * radius; its value is computed first and this value is copied into r. The return type is double. The signature is circleArea(double); the return type and the parameter name are not part of the signature.

  2. Three methods are defined as follows: a() first prints “a1 ”, then calls b(), then prints “a2 ”. b() prints “b1 ”, calls c(), prints “b2 ”. c() only prints “c ”. main calls a(). What is the output? What is the largest number of frames on the stack?

    Answer

    The output is a1 b1 c b2 a2. Each method waits until the method it called finishes and then continues where it left off. While c is running there are 4 frames on the stack: main, a, b and c. The frames close in the reverse of the order in which they were opened: first c, then b, and a last.

  3. For the method static void zeroOut(int n) { n = 0; }, what does int k = 9; zeroOut(k); System.out.println(k); print? How should the method and the call be changed to really zero k?

    Answer

    It prints 9. Java passes by value: n is a copy of k, and n = 0 changes only the copy. When the method ends, n is deleted. The method is written to return a value, static int zeroOut() { return 0; }, and the caller does the assignment itself: k = zeroOut();. In this example, however, the simplest solution is not to use a method at all and write k = 0;.

  4. A class has only static void g(long x) and static void g(double x); both print the type and value of their parameter. Which method do the calls g(5), g(5.5f) and g('x') run?

    Answer

    There is no exact match for any of the calls; the compiler chooses the closest widening. g(5): int → long is closer than to double; long 5 is printed. g(5.5f): float cannot be narrowed to long but widens to double; double 5.5 is printed. g('x'): the long version is chosen through the widening char → int → long; since the code of the character 'x' is 120, long 120 is printed.

  5. For static int count(int... s) { return s.length; }, what do count(), count(5), count(new int[]{1, 2, 3}) and count(1, 2) return? Why does the header static int count(int... s, int k) not compile?

    Answer

    0, 1, 3 and 2, respectively. In the call with no arguments an empty array is passed (its length is 0); if an array is given directly, that array is used. In the second header the varargs parameter is not at the end of the list; the compiler gives the error varargs parameter must be the last parameter, because it cannot know which of the values in the call goes to k.

  6. Which line of the following method gives a compile error, and why? static int sumOfSquares(int n) { for (int i = 1; i <= n; i++) { int sq = i * i; } return sq; }

    Answer

    The line return sq; gives a cannot find symbol error. sq is declared in the body block of the for loop, and its scope ends when the block closes; outside the loop there is no variable with this name. The method also does not achieve its purpose: the squares are not being accumulated. The correct form is to declare int total = 0; before the loop, write total += i * i; in the body, and finish with return total;.

  7. In how many iterations does gcd(105, 30) finish with Euclid's algorithm, and what does it return? What does the lcm method return for the same numbers?

    Answer

    Iteration 1: 105 % 30 = 15 (105 = 3 × 30 + 15); a = 30, b = 15. Iteration 2: 30 % 15 = 0; a = 15, b = 0. The condition becomes false and 15 is returned after 2 iterations. lcm = 105 / 15 × 30 = 7 × 30 = 210. Check: 210 = 2 × 105 = 7 × 30.

  8. In the call isPrime(91), how many iterations does the loop run and what is returned? How many iterations does isPrime(37) run?

    Answer

    91 = 7 × 13. For i = 2, 3, 4, 5, 6 the condition (i ≤ 91 / i) is true and the remainder is not 0. At i = 7, 7 ≤ 91 / 7 = 13 is true and 91 % 7 = 0: false is returned in the 6th iteration. For 37, i = 2…6 is tried (5 iterations); at i = 7, 7 ≤ 37 / 7 = 5 is false and true is returned.

  9. What do Math.round(3.5), Math.round(-3.5), Math.abs(-0.5) and Math.max(-1, -8) return? Why does int r = Math.round(3.5); not compile?

    Answer

    4, −3, 0.5 and −1. Numbers exactly at the half are rounded to the larger value: 3.5 → 4, −3.5 → −3. Math.abs returns double for a double argument. −1 is greater than −8. Because Math.round(double) returns long, the result cannot be assigned directly to an int (possible lossy conversion from long to int); int r = (int) Math.round(3.5); must be written.

  10. For static int triple(int x) { return 3 * x; }, what do triple(triple(2)) and triple(2) * triple(1) give? If the same method printed with System.out.println(3 * x) instead of returning the result, could these two expressions be written?

    Answer

    The first: the inner call gives 6, the outer triple(6) = 18. The second: 6 × 3 = 18. Both are 18. If the method were a void method that printed, neither expression would compile: a void call can be neither an argument to another call nor an operand of a multiplication. A pure method that returns its result can be used in any expression.

9.16Further reading

  • Oracle, The Java Tutorials: the pages “Defining Methods” and “Passing Information to a Method or a Constructor”; method declaration, overloading, varargs and pass by value are explained with short examples.
  • R. Sedgewick and K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), Section 2.1 “Static Methods”: static methods, scope and modular programming with methods, worked through with examples from scientific computing.
  • A. B. Downey and C. Mayfield, Think Java (2nd ed., O'Reilly, 2019): methods, parameters and return values are explained with stack diagrams for people new to programming; the online version of the book is free.
  • Oracle, Java Language Specification, Java SE 21, §8.4 “Method Declarations” and §15.12 “Method Invocation Expressions”: the exact rules for the signature, return, and how the compiler chooses among overloads.

9.17References

  1. P. Deitel, H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
  2. Y. D. Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
  3. Oracle, The Java Tutorials: Defining Methods; Passing Information to a Method or a Constructor.
  4. Oracle, Java Language Specification, Java SE 21 Edition, Chapter 8: Classes (§8.4 Method Declarations).
  5. R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 2.1 Static Methods.
  6. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.

Related pages: Chapter 9 slides · Study questions · Method Call Stack simulator · Glossary · © Sercan Külcü. All rights reserved.