Object-Oriented Programming with Java · Lecture Notes
Chapter 3.2: Methods
As a program grows, it no longer fits inside a single main method. The same calculation is needed in several places, and bugs get lost in a long pile of code. The method is the answer to both problems: write a job once, give it a name, and call it as often as you like. In Java every function lives inside a class and is called a method. These notes show how a method is defined and called, what happens in memory during a call, and why arguments are copied. They also cover how the compiler chooses between methods with the same name, the built-in Java methods, and the scope and lifetime of variables. The last sections discuss how to design a good method. Every program in the examples was compiled and run with JDK 21; the values in the trace tables and the compiler messages come from those runs.
Learning outcomes
- Defining and calling
- Write a method with an access modifier, a return type, a name and a parameter list; call it with arguments and use the value it returns.
- Tracing execution
- Show step by step how stack frames are pushed and popped on the call stack and how arguments are copied by value.
- Overloading
- Tell apart methods that share a name by their parameter lists, and predict from the argument types which version the compiler will pick.
- Built-in methods
- Use the methods of
System.outandMathcorrectly, and recognize the commonly used classes and packages of the Java library. - Scope
- Explain the scope and lifetime of local variables, class fields and nested blocks; spot shadowing.
- Design
- Design good methods using abstraction, generalization, DRY and the single-responsibility principle; split a problem into methods.
3.2.1The function concept
So far every program has consisted of a single method: main. For short programs that is enough. But consider a student grade system. Grades are read, the average is computed, a letter grade is found, and the results are printed. If all of these steps are written one after another inside main, the result is one block of several hundred lines. If the average formula is needed in three places, it gets copied three times, and when the formula turns out to be wrong, all three copies must be fixed separately. Methods remove this mess.
3.2.1.1What is a function?
A function is a named piece of code that does one job and can be used again and again. It is defined by the parameters it takes and the type of the value it returns. In Java every function is written inside a class and is called a method.
A function is like a recipe. “Brew tea” is a recipe: it is written once and followed as often as needed. The ingredients are the inputs of the recipe; their counterpart in programming is the parameters. The tea that comes out is the result of the recipe; its counterpart is the return value. Whoever follows the recipe does not rethink every step; they just say “brew tea” and get the result. A program does the same: it calls a method by name and uses its result.
A function is not really a new idea. main, which every Java program has, is a method. System.out.println(...), used to print text, is a call to a method that comes with the Java library. The programmer does not know how println sends characters to the screen; they only know what it does. These notes show how to build the same structure with your own methods.
The benefits of using methods can be listed as follows:
- Readability. A well-named method call says in one line what is being done. Someone reading
computeAverage(grades)understands what happens without looking at the details of the loop. - Less duplicated code. The same job is written once and called whenever it is needed. When a bug appears, only one place has to be fixed.
- Modularity. The program is split into small, manageable pieces. Each piece can be written and tested separately.
- Structure. The links between the pieces are limited to parameters and return values. When the inside of one piece changes, the others are not affected.
In these notes the words “function” and “method” are mostly used interchangeably. The distinction is this: a function is the general programming concept, and a method is its form in Java. In languages such as C, functions can be written without belonging to any class. In Java, a method cannot be written outside a class.
3.2.1.2Input, process, output
Every function can be thought of in three stages. In the input stage the function is given data; these data are the parameters, and they determine what the function works on. In the process stage the statements in the body of the function work on the input. In the output stage a result is produced and handed back to the caller with the return statement. Figure 3.2.1 shows the three stages for the add function.
num1 = 5, num2 = 3) enter the add function. The body performs result = num1 + num2. return 8 hands the result back to the caller.This diagram is the same as the function concept in mathematics. In the function f(x) = x², x is the input, squaring is the process, and x² is the output. When f(3) is written, 3 is put in place of x and the result is 9. A function in programming works the same way: it takes the input, computes, and gives the result.
Functions in programming differ from those in mathematics in two ways. First, some functions have no input. A function that prints a fixed greeting needs no data at all. Second, some functions return no value; their job is to leave an effect, such as writing to the screen. Java marks this case with the keyword void. In English “void” means “empty”: the method gives nothing back.
3.2.2Defining and calling methods
There are two separate steps in using a method. First the method is defined: its name, inputs, result type and body are written down. A definition on its own runs nothing; it only records the recipe. Then the method is called: control moves to the method, the body runs, and control returns to the place where the call was made. A method is defined once but can be called as many times as needed.
3.2.2.1Parts of a method header
A method definition has two parts: the header and the body. Figure 3.2.2 shows the parts of the add method, which adds two numbers, one by one.
public), the return type (int), the method name (add) and the parameter list. The name together with the parameter types forms the signature of the method. The part between the braces is the body.| Part | In the example | Role |
|---|---|---|
| Access modifier | public | Says who may call the method. public means it can be called from anywhere. |
| Return type | int | The type of the value the method gives back. A method that returns no value uses void. |
| Method name | add | The name used when the method is called. It is a verb or verb phrase and starts with a lowercase letter. |
| Parameter list | (int num1, int num2) | The inputs of the method. The type and name of each parameter are written out, and parameters are separated by commas. |
| Body | { ... } | The statements that run when the method is called. |
Other modifiers can appear between the access modifier and the return type. The one seen most often in these notes is static, which says the method can be called without an object. The order in a header is fixed: modifiers first, then the return type, then the name, and finally the parameter list. The access modifier may be omitted; the method can then be called only from classes in the same package. The return type, however, can never be left out.
Java's naming convention is camelCase: the first word starts with a lowercase letter and the first letter of each following word is capitalized. computeAverage, isPrime and readGrades follow this rule. Because a method does something, its name states an action. For methods that return boolean, the name often reads like a question: isPrime(17) answers the question “is 17 prime?”.
The method signature is the name of the method together with the sequence of its parameter types. The signature of add is add(int, int). The return type, the parameter names and the access modifier are not part of the signature.
The signature matters in two places. First, the compiler looks at the signature to decide which method a call refers to. Second, a class cannot contain two methods with the same signature. This rule decides when methods with the same name can be written side by side.
The compiler catches most mistakes made when writing a header. Three typical examples and the messages JDK 21 gives for them follow. In the first, the type of the second parameter has been forgotten. In mathematics, saying “let a, b be integers” is normal, but in Java every parameter carries its own type:
public class CommaParam {
static int sum(int a, b) { return a + b; }
}CommaParam.java:2: error: <identifier> expected
static int sum(int a, b) { return a + b; }
^
1 errorIn the second, the return type is missing. The compiler accepts a header without a return type only for a constructor, whose name is the same as the class name. A constructor is a special method that runs when an object is created. Since sum is not the name of the class, an error is reported:
public class UntypedMethod {
static sum(int a, int b) { return a + b; }
}UntypedMethod.java:2: error: invalid method declaration; return type required
static sum(int a, int b) { return a + b; }
^
1 errorIn the third, the return type has been written before the modifier. The compiler expects a name after int, and when it meets static it reports two separate errors:
public class StaticOrder {
int static sum(int a, int b) { return a + b; }
}StaticOrder.java:2: error: <identifier> expected
int static sum(int a, int b) { return a + b; }
^
StaticOrder.java:2: error: invalid method declaration; return type required
int static sum(int a, int b) { return a + b; }
^
2 errorsAnother rule is that methods cannot be nested. Every method is written in the body of the class, outside the other methods. If a method definition is placed inside main, the compiler sees it as a meaningless expression:
public class NestedCalls {
public static void main(String[] args) {
static int square(int n) { return n * n; }
}
}NestedCalls.java:3: error: illegal start of expression
static int square(int n) { return n * n; }
^
NestedCalls.java:5: error: class, interface, enum, or record expected
}
^
2 errorsThe order of methods in a class, on the other hand, does not matter. main can be written at the top with the helper methods below it, or the other way around. The compiler reads the whole class before it matches the calls.
3.2.2.2Call, parameter and argument
To run a method you have defined, you write its name followed by its inputs in parentheses. The following program defines the add method and calls it from main.
public class AddExample {
public static int add(int num1, int num2) {
int result = num1 + num2;
return result;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println("Sum: " + result);
}
}Sum: 8A method call runs a method with arguments. A parameter is the variable in the method definition that stands for an input. An argument is the actual value given to the parameter at the time of the call.
In the program, the expression add(5, 3) is a call. The 5 and 3 in the call are arguments; num1 and num2 in the definition are parameters. An easy way to remember the difference: a parameter is written in the definition and has a name, while an argument is written in the call and has a value. At the moment of the call the values of the arguments are copied into the parameters in order: num1 = 5, num2 = 3.
When the call is made, control goes to the method. The body runs, result becomes 8, and return result; gives this value back. Control returns to the place where the call was made. The expression add(5, 3) now has the value 8, and this value is assigned to the variable result in main. The println on the last line is also a method call; its argument is the expression "Sum: " + result, and Sum: 8 is printed.
Arguments must agree with the parameters in three respects: number, order and type. If a method with two parameters is given a single argument, the compiler rejects the call and prints the expected types next to the supplied ones:
public class MissingArgument {
static int add(int num1, int num2) { return num1 + num2; }
public static void main(String[] args) {
int s = add(5);
}
}MissingArgument.java:4: error: method add in class MissingArgument cannot be applied to given types;
int s = add(5);
^
required: int,int
found: int
reason: actual and formal argument lists differ in length
1 errorIn the message, the line required: int,int shows the types the method expects, and found: int shows what the call supplied. The reason line says that the problem is the number of arguments. A type mismatch is also an error. In the call add(5, 2.5), 2.5 is a double, which does not fit into an int parameter without losing information:
ArgumentType.java:4: error: incompatible types: possible lossy conversion from double to int
int s = add(5, 2.5);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorThe conversion in the opposite direction is allowed. An int argument can be given to a method with a double parameter; the value is automatically widened to double. This rule also determines the compiler's choice in overloading.
An argument does not have to be a constant number; it can be a variable or any expression. In the call square(a + 1), Java first evaluates the expression a + 1. If a is 3, the value of the argument is 4, and this 4 is copied into the parameter. The method sees neither the variable a nor the expression a + 1; it receives only the value 4. This rule is the basis of the topic of copying arguments.
3.2.2.3Tracing a call step by step
To understand what happens in memory when a method is called, two concepts are needed: the stack frame and the call stack.
A stack frame is the memory record that holds the parameters and local variables of one method call. The call stack is the structure that keeps the frames of the running methods on top of one another. Each call pushes a new frame onto the top of the stack; when the method finishes, its frame is removed from the stack.
A stack is like a pile of plates. The last plate put down is on top and is the first one taken. On the call stack, too, the frame of the most recently called method is on top. The running method always owns the topmost frame. When that method finishes, its frame is removed and the method below it continues where it left off.
The execution of the previous program is given step by step in Table 3.2.2. The line numbers follow the code layout of the trace slide in the lecture slides: lines 1–4 are the add method and lines 6–9 are the main method.
| Step | Line | Call stack | Variables | Output |
|---|---|---|---|---|
| 1 | 6: public static void main(String[] args) { | main() | args=[] | — |
| 2 | 7: int result = add(5, 3); | main() → add(5, 3) | num1=5, num2=3 | — |
| 3 | 2: int result = num1 + num2; | main() → add(5, 3) | num1=5, num2=3, result=8 | — |
| 4 | 3: return result; | main() → add(5, 3) | num1=5, num2=3, result=8, return=8 | — |
| 5 | 7: int result = add(5, 3); | main() | args=[], result=8 | — |
| 6 | 8: System.out.println("Sum: " + result); | main() | args=[], result=8 | Sum: 8 |
In the first step the stack contains only the frame of main. A program always starts at the main method; args is the array that holds the command-line arguments, and here it is empty. In the second step add(5, 3) is called. A new frame is opened on top of the stack, and the arguments are copied into the parameters in this frame.
In the third step the body runs: result = 5 + 3 = 8. This result is a local variable of add and lives in the frame of add. Figure 3.2.3 shows this moment. The frame of main also has a variable named result, but its value is not yet known. The two variables have the same name, yet they are separate variables living in different frames.
add(5, 3) is running: the top frame holds num1 = 5, num2 = 3, result = 8; in the main frame below, result is still undefined. On the right the method has returned and its frame is gone; result in main is now 8.In the fourth step return result; runs. The value 8 is sent to the caller, the method ends, and its frame is removed from the stack. Together with the removed frame, num1, num2 and the result of add disappear. In the fifth step control returns to line 7, where the call was made; the returned 8 is assigned to the variable result of main. In the sixth step println is called and Sum: 8 is printed. println is a method too; for the short time it runs, a frame for it is pushed onto the stack and popped again.
The lesson of this trace is that a method call is control temporarily going somewhere else and coming back. A new workspace is opened at the destination, and when the job is done this workspace is cleaned up. Only the value sent with return remains.
3.2.2.4Methods that return a value and methods that do not
The following program contains three methods that differ in their input and output.
public class ExampleMethods {
// Addition method
public static int add(int num1, int num2) {
return num1 + num2;
}
// Squaring method
public static double square(double num) {
return num * num;
}
// Hello world method
public static void helloWorld() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
System.out.println(add(2, 7));
System.out.println(square(1.5));
helloWorld();
}
}9
2.25
Hello, World!| Method | Input | Output | Use of the call |
|---|---|---|---|
add | 2 × int | int | println(add(2, 7)) → 9 |
square | 1 × double | double | println(square(1.5)) → 2.25 |
helloWorld | none | none (void) | helloWorld(); as a statement on its own |
This time add returns the result directly without an intermediate variable: return num1 + num2;. Java first evaluates the expression and then returns the value. The two ways of writing it, with and without the intermediate variable, give the same result.
The call square(1.5) returns 1.5 × 1.5 = 2.25, and 2.25 is printed. Java writes decimal numbers with a point, both in code and in println output. The method helloWorld has neither a parameter nor a return value. The parentheses are still written: helloWorld() in the definition and helloWorld(); in the call. Writing helloWorld; without parentheses is a compile error, because Java does not recognize a name as a method call unless it sees parentheses.
The real difference between the two kinds of method is in how the call is used. A call to a method that returns a value is an expression; it has a value. This value can be assigned to a variable, used in another calculation, or passed as an argument to another method: in println(add(2, 7)) the result of add becomes the argument of println. A call to a void method has no value. It can be written only as a statement on its own.
A method that returns a value can also be called on its own: add(2, 7); is a valid statement. But because the returned value is not assigned anywhere, it is lost. The compiler gives no warning in this case. That is why, in most complaints of the form “I called the method but the result did not change”, the returned value was never assigned to a variable.
3.2.3return and void
The return statement gives the result of a method to the caller. Its rules are simple, but it is one of the places where beginners argue most with the compiler. This section explains how return works, when the type of the returned value is accepted, and how the compiler checks the rule “every path must end in a return”.
3.2.3.1The return statement
The return value is the value the method gives to the caller with return. The return type is the type of this value; it is written in the header before the method name. If the method returns no value, the return type is void.
The statement return expression; has two effects. First, the value of the expression is computed and handed to the caller. Second, the method ends immediately. Lines after return do not run. This property is used to leave a method early.
A void method returns no value, but it can still end early. For that, a bare return; is written. The following program checks the divisor before dividing. If the divisor is zero, it prints a warning and leaves the method at once.
public class EarlyReturn {
static void printQuotient(int dividend, int divisor) {
if (divisor == 0) {
System.out.println("Cannot divide by zero!");
return; // leave the method at once
}
System.out.println(dividend / divisor);
}
public static void main(String[] args) {
printQuotient(10, 2);
printQuotient(7, 0);
}
}5
Cannot divide by zero!In the first call divisor is 2. The if condition is false, its body is skipped, and the result of 10 / 2, which is 5, is printed. In the second call divisor is 0. The condition is true; the warning is printed and return; ends the method. The line println(dividend / divisor) is never reached. Had it been reached, the integer division would have tried to divide by zero and the program would have stopped with ArithmeticException: / by zero.
The same method could have been written with else. The advantage of the early-return pattern is that it filters out the bad cases at the start of the method and leaves the real work unindented. As the number of conditions to check grows, this style is more readable than nested ifs.
Writing a statement right after return in the same block is a compile error. The compiler sees that this statement cannot be reached by any path and reports unreachable statement:
public class Unreachable {
static int f(int n) {
return n * 2;
System.out.println("done");
}
}Unreachable.java:4: error: unreachable statement
System.out.println("done");
^
1 error3.2.3.2Matching the return type
The type of the value that return returns must be compatible with the return type declared in the header. The compatibility rule is the same as for assignment: a value can be returned if it can be assigned to a variable of the return type. So an int value can be returned from a method with return type double; the value is widened automatically. The opposite means a loss of information, and the compiler does not accept it:
public class Narrowing {
static int half(double x) { return x / 2; }
}Narrowing.java:2: error: incompatible types: possible lossy conversion from double to int
static int half(double x) { return x / 2; }
^
1 errorBecause widening is free, a trap arises that compiles but gives a wrong result. Both of the following methods return double, but their results differ.
public class Widening {
// the int result is widened to the double return type
static double half(int n) {
return n / 2;
}
static double halfFixed(int n) {
return n / 2.0;
}
public static void main(String[] args) {
System.out.println(half(7));
System.out.println(halfFixed(7));
}
}3.0
3.5In half(7), n / 2 is a division between two ints. Integer division discards the fraction and the result is 3. Making the return type double does not change this calculation; the value 3 is widened to 3.0 as it is returned. In other words, the return type decides not how the expression is evaluated, but which type the computed result is converted to. For the correct result the division itself must be made floating-point: the expression n / 2.0 gives 3.5.
void and returning a value exclude each other. A value cannot be returned with return from a void method. Nor can a bare return; be written in a method that returns a value. The compiler gives separate messages for the two cases:
public class VoidValue {
static void greet() { return "Hello"; }
}VoidValue.java:2: error: incompatible types: unexpected return value
static void greet() { return "Hello"; }
^
1 errorpublic class IntBareReturn {
static int twice(int n) { int s = n * 2; return; }
}IntBareReturn.java:2: error: incompatible types: missing return value
static int twice(int n) { int s = n * 2; return; }
^
1 errorTrying to use the result of a void method is also an error. Since a call to a void method has no value, it can be neither assigned to a variable nor passed as an argument to println:
public class VoidUse {
static void sayHello() { System.out.println("Hi"); }
public static void main(String[] args) {
int x = sayHello();
}
}VoidUse.java:4: error: incompatible types: void cannot be converted to int
int x = sayHello();
^
1 errorVoidPrint.java:4: error: 'void' type not allowed here
System.out.println(sayHello());
^
1 error3.2.3.3Every path must end in a return
In a method that returns a value, every path that control can follow must end in a return. If control can reach the closing brace at the end of the method without passing through any return, the compiler says missing return statement. The most surprising form of the error appears in chains of conditions that look complete to a human:
public class MissingReturn {
static int sign(int n) {
if (n > 0) return 1;
if (n <= 0) return -1;
}
}MissingReturn.java:5: error: missing return statement
}
^
1 errorTo a human, the conditions n > 0 and n <= 0 cover all integers; one of the two is certainly true. The compiler, however, does not reason about the values of conditions. It looks only at the structure: there are two ifs, and both are treated as if they could be false. Control can then reach the end of the method, and there is no return there. The same error appears with an if/else if chain; as long as the last branch is an else if, the compiler assumes the chain can be left somewhere.
The fix is to turn the last condition into a plain else, or to put a default return at the end of the method:
static int sign(int n) {
if (n > 0) return 1;
return -1; // every case with n <= 0 ends up here
}void methods have no such requirement. When control reaches the end of the method, the method ends by itself; writing return; at the end is unnecessary.
3.2.4static methods and calls through an object
Every method so far had the word static in its header. This word determines how the method is called. Without going into the details of objects, it is enough for now to tell the two forms of call apart.
A static method belongs to the class, not to an object. No object is needed to call it. It is called by its name from inside the same class, and from another class in the form ClassName.method(). A method that is not static is called through an object: object.method().
The most familiar example of a static method is the Math class. To take a square root, no Math object is created; you simply write Math.sqrt(16). Inside the same class there is no need to write the class name:
static int add(int num1, int num2) {
return num1 + num2;
}
// inside main, directly:
int result = add(5, 3);To call a method that is not static, you first create an object of that class with new, and then call the method through the object:
public class Calculator {
int add(int num1, int num2) {
return num1 + num2;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
int result = calc.add(5, 3);
System.out.println(result); // 8
}
}8The line Calculator calc = new Calculator(); creates an object of the Calculator class and reaches it through a variable named calc. The call calc.add(5, 3) runs the method on this object. The dot means “the method of this object”. The result is again 8.
If the two forms are mixed up, the compiler reports an error. main is a static method; while it runs, no object exists yet. Calling a non-static method directly from main leaves the question “whose method?” unanswered:
public class StaticContext {
int add(int num1, int num2) { return num1 + num2; }
public static void main(String[] args) {
int result = add(5, 3);
}
}StaticContext.java:4: error: non-static method add(int,int) cannot be referenced from a static context
int result = add(5, 3);
^
1 error“Static context” in the message means the inside of a static method. There are two ways to fix it: either add static to the header of the method, or create an object and call the method through it. Because the methods in this chapter do not need the state of an object, all of them are written static.
This also explains why main itself is static. When the program starts, the JVM (Java Virtual Machine) has not created any object yet. For it to call main without needing an object, the method must belong to the class.
3.2.5Pass by value
Can a method change a variable that is given to it as an argument? The answer is one of the most misunderstood points in Java. The short answer is no. The method receives a copy of the argument, not the argument itself. But for arrays and objects the thing that is copied is a reference, so the situation looks different at first sight. This section follows the two cases separately.
Pass by value means that at the time of the call the value of the argument is copied and given to the parameter. Java passes all arguments by value. If the argument is an array or an object, the value that is copied is the reference that points to the location of that array or object.
3.2.5.1A primitive argument
In the following program both main and increase have a variable named num. increase adds 10 to its own num.
static void increase(int num) {
num = num + 10;
System.out.println("increase: " + num);
}
public static void main(String[] args) {
int num = 5;
increase(num);
System.out.println("main: " + num);
}increase: 15
main: 5The program prints increase: 15 and main: 5. The num in main has not changed. Table 3.2.4 shows why, step by step.
| Step | Line | Call stack | Variables | Output |
|---|---|---|---|---|
| 1 | 7: int num = 5; | main() | num=5 | — |
| 2 | 8: increase(num); | main() → increase(5) | num=5 | — |
| 3 | 2: num = num + 10; | main() → increase(5) | num=15 | — |
| 4 | 3: System.out.println("increase: " + num); | main() → increase(5) | num=15 | increase: 15 |
| 5 | 9: System.out.println("main: " + num); | main() | num=5 | main: 5 |
In the second step increase(num) is called. Java reads the value of the argument variable num: 5. In the newly opened frame a separate box is set aside for the parameter of increase, and 5 is copied into this box. There are now two separate nums in memory: one in the frame of main and one in the frame of increase. It does not matter that their names are the same; Java keeps the variables of each frame apart.
increase is running: in the top frame the copy has become 15, while in the main frame below num is still 5. On the right the method has finished; the copy was removed along with the frame, and the 5 in main is untouched.In the third step num = num + 10; runs. Because this line runs in the topmost frame, that is, inside increase, it changes only the copy: the copy becomes 15. In the fourth step increase: 15 is printed. In the fifth step the method ends; its frame, and with it the copy, is removed. When control returns to main, the num of main is 5, exactly as untouched as before.
The only way to carry the method's change back to main is return. increase is written so that it returns the new value, and the caller assigns this value to its own variable:
static int increase(int num) {
return num + 10;
}
// inside main:
num = increase(num); // num in main is now 15Here too the method does not touch the variable of main. The one that makes the change is main itself, which writes the assignment. This arrangement makes programs safe: when a method is called, it is certain that the local variables of the caller will not change.
3.2.5.2An array argument: a copy of the reference
With methods that take an array parameter the situation looks different. First you need to know where an array lives in memory. In Java, memory is divided into two regions. Frames and local variables live on the stack. Arrays and objects are kept in a separate region called the heap. An array variable holds not the array itself but a reference to the location of the array on the heap.
The following method takes an array and an int. It tries to change the array and the integer, and then assigns a brand new array to its parameter.
static void modify(int[] d, int x) {
d[0] = 50;
x = 50;
d = new int[2];
d[1] = 50;
}
public static void main(String[] args) {
int[] a = {1, 2};
int x = 1;
modify(a, x);
System.out.println(a[0] + " " + a[1] + " " + x);
}50 2 1The program prints 50 2 1: the first element of the array has changed, the second has not, and x has not changed at all. Table 3.2.5 shows the state of the two arrays and the two x variables at each step. In the table, the array created in main is called A and the new array created inside the method is called B.
| Step | Line | a → array | d → array | x (main) | x (modify) |
|---|---|---|---|---|---|
| 1 | 9: int[] a = {1, 2}; | A {1, 2} | — | — | — |
| 2 | 10: int x = 1; | A {1, 2} | — | 1 | — |
| 3 | 1: static void modify(int[] d, int x) { | A {1, 2} | A {1, 2} | 1 | 1 |
| 4 | 2: d[0] = 50; | A {50, 2} | A {50, 2} | 1 | 1 |
| 5 | 3: x = 50; | A {50, 2} | A {50, 2} | 1 | 50 |
| 6 | 4: d = new int[2]; | A {50, 2} | B {0, 0} | 1 | 50 |
| 7 | 5: d[1] = 50; | A {50, 2} | B {0, 50} | 1 | 50 |
| 8 | 11: modify(a, x); | A {50, 2} | — | 1 | — |
| 9 | 12: System.out.println(a[0] + " " + a[1] + " " + x); | A {50, 2} | — | 1 | — |
In the first step int[] a = {1, 2}; creates an array of two elements on the heap; a holds the reference to this array. In the second step x = 1. Because it is a primitive value, the 1 is stored directly in the frame of main.
In the third step modify(a, x) is called and both arguments are passed by value. d is given a copy of the reference in a; the x of modify is given a copy of 1. The reference has been copied, but the array has not. a and d now point to the same array A on the heap. The first part of Figure 3.2.5 draws this moment: two arrows in two separate frames reach the same array.
d[0] = 50; a and d point to the same array, and the change is written to the shared array. Middle: after d = new int[2] and d[1] = 50; d now points to the new array, and the link is broken. Bottom: the method has ended; no reference to the new array is left.In the fourth step d[0] = 50; runs. This assignment changes not the variable d but the first cell of the array that d points to. Because d and a point to the same array, the change is visible from main too. In the fifth step x = 50; changes only the copy in modify; the x in main stays 1.
In the sixth step d = new int[2]; creates a new array B on the heap and assigns the reference to this array to d. This assignment changes d itself. Because d is a copy, a is not affected; a still points to A. The link between d and a is broken on this line. The d[1] = 50; in the seventh step writes to the new array; array A does not change.
In the eighth step the method ends and its frame is removed. The only reference to array B was d; now no variable points to B. Such an array can never be reached from the program again. The JVM's garbage collector reclaims the memory of such objects when the time comes. In the ninth step a[0], a[1] and x are printed: 50 2 1.
The rule that follows from this example is the following. Java passes everything by value; a reference is also a value that is copied. A method can change the array that the reference it received points to, because the array is shared. But assigning a new array to the parameter does not change the caller's variable, because the parameter is only a copy. Some sources write that Java passes objects “by reference”. This statement is wrong: with true pass by reference, the line d = new int[2] would have changed a in main as well.
3.2.5.3The swap trap
The best-known consequence of pass by value is that a method that exchanges the values of two variables cannot be written in Java. In the following program there are two versions of the swap method. The first takes two ints; the second takes an array and two indices.
import java.util.Arrays;
public class Swap {
static void swap(int x, int y) {
int tmp = x;
x = y;
y = tmp;
}
static void swap(int[] d, int i, int j) {
int tmp = d[i];
d[i] = d[j];
d[j] = tmp;
}
public static void main(String[] args) {
int[] arr = {4, 7, 9};
swap(arr[0], arr[2]);
System.out.println(Arrays.toString(arr));
swap(arr, 0, 2);
System.out.println(Arrays.toString(arr));
}
}[4, 7, 9]
[9, 7, 4]The first call is swap(arr[0], arr[2]). The arguments are the values of the expressions arr[0] and arr[2], that is, 4 and 9. The method swaps these two copies inside itself: x becomes 9 and y becomes 4. When the method ends, the copies are removed and the array stays unchanged: [4, 7, 9].
The second call takes the array and the indices. This time the method writes to the cells of the array that the reference points to: d[0] becomes 9 and d[2] becomes 4. Because the array is shared, the change is visible from main: [9, 7, 4]. Arrays.toString is a built-in method that prints an array in square brackets.
The behavior of pass by value can also be followed step by step in the Pass-by-Value Lab simulator. The simulator draws the passing of a primitive value, an array, and an object separately on the call stack and the heap.
3.2.6Method overloading
Sometimes the same job has to be done with inputs of different types or in different numbers. Consider methods that add two integers, two floating-point numbers and three integers. It is possible to give each a separate name: sumTwoInts, sumTwoDoubles, sumThreeInts. But such names make use harder; the programmer has to remember the right name every time. Java allows the same name to be used for several methods.
3.2.6.1Same name, different parameter list
Method overloading means defining several methods with the same name in the same class. The parameter lists of the methods must differ: in the number, the types or the order of the parameters. In other words, overloaded methods have different signatures.
public class Overloading {
static int sum(int a, int b) {
return a + b;
}
static double sum(double a, double b) {
return a + b;
}
static int sum(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(sum(2, 3));
System.out.println(sum(2.5, 1.2));
System.out.println(sum(1, 2, 3));
}
}5
3.7
6The class has three sum methods. Their signatures are sum(int, int), sum(double, double) and sum(int, int, int); all three differ from each other. The call sum(2, 3) carries two int arguments and runs the first method: 5. sum(2.5, 1.2) carries two doubles and runs the second: 3.7. sum(1, 2, 3) carries three arguments and runs the third: 6. The different appearance of 5 and 3.7 in the output also gives away the method chosen: the result of the method that returns int is printed without a decimal point.
It is the compiler that decides which method will run. The decision is made before the program runs, at compile time, and only by looking at the types of the arguments. In the compiled program every call is already bound to a specific method.
The Java library uses overloading heavily. println is not a single method: println(int), println(double), println(String), println(char), println(boolean) and the parameterless println() are defined separately. The programmer sees them all as a single name and uses the same name whatever type is printed. Math.abs and Math.max are also overloaded separately for int, long, float and double.
The criterion for overloading is the signature, and the return type is not part of the signature. For this reason two methods that differ only in their return type cannot exist in the same class:
public class ReturnType {
static int f(int a) { return a; }
static double f(int a) { return a; }
}ReturnType.java:3: error: method f(int) is already defined in class ReturnType
static double f(int a) { return a; }
^
1 errorThe reason for the rule is clear. In a call such as f(5); that does not use the returned value, the compiler could not tell which of the two methods to choose. Different parameter names are not enough either: sum(int a, int b) and sum(int x, int y) have the same signature.
3.2.6.2Which version does the compiler choose?
When the types of the arguments are exactly the same as the parameters, the choice is easy. The hard part is what happens when there is no exact match. In that case the compiler looks for methods that fit by widening the arguments. The widening conversions in Java follow this order:
byte → short → int → long → float → double and char → int
A type can automatically widen to every type that comes after it in this chain. Narrowing conversions in the opposite direction are never made automatically. The choice can be thought of in three steps:
- Methods whose number of parameters differs from the number of arguments are eliminated.
- Of the remaining methods, those in which each argument either has the same type or fits by widening are considered applicable.
- If several methods are applicable, the compiler chooses the most specific one. A method is more specific if all its parameter types can widen to the parameter types of the other. The
(int, int)version is more specific than(double, double), becauseintwidens todouble.
The following program tries the same three methods with four different calls. Its output and trace follow.
static int sum(int a, int b) {
return a + b;
}
static double sum(double a, double b) {
return a + b;
}
static int sum(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(sum(4, 6));
System.out.println(sum(4, 2.5));
System.out.println(sum(7, 1, 2));
System.out.println(sum('A', 1));
}10
6.5
10
66| Step | Line | Call stack | Variables | Output |
|---|---|---|---|---|
| 1 | 11: System.out.println(sum(4, 6)); | main() | — | — |
| 2 | 2: return a + b; | main() → sum(int, int) | a=4, b=6 | — |
| 3 | 11: System.out.println(sum(4, 6)); | main() | — | 10 |
| 4 | 12: System.out.println(sum(4, 2.5)); | main() | — | — |
| 5 | 5: return a + b; | main() → sum(double, double) | a=4.0, b=2.5 | — |
| 6 | 12: System.out.println(sum(4, 2.5)); | main() | — | 6.5 |
| 7 | 13: System.out.println(sum(7, 1, 2)); | main() | — | — |
| 8 | 8: return a + b + c; | main() → sum(int, int, int) | a=7, b=1, c=2 | — |
| 9 | 13: System.out.println(sum(7, 1, 2)); | main() | — | 10 |
| 10 | 14: System.out.println(sum('A', 1)); | main() | — | — |
| 11 | 2: return a + b; | main() → sum(int, int) | a=65, b=1 | — |
| 12 | 14: System.out.println(sum('A', 1)); | main() | — | 66 |
The first call is sum(4, 6); the arguments are (int, int). The version with three parameters is eliminated because of the count. (int, int) is an exact match; (double, double) also fits by widening. The most specific, (int, int), is chosen and 10 is printed. The first part of Figure 3.2.6 shows this choice.
sum(4, 6): (int, int) is an exact match. Middle, sum(4, 2.5): 2.5 cannot be narrowed to int, so (int, int) is eliminated; 4 is widened and (double, double) is chosen. Bottom, sum('A', 1): char can widen to both versions; the most specific, (int, int), is chosen.The second call is sum(4, 2.5); the arguments are (int, double). The (int, int) version does not fit, because 2.5 cannot be converted implicitly to int. (double, double) fits: the value 4 is widened to 4.0. The method runs with a = 4.0, b = 2.5 and returns 6.5.
The third call sum(7, 1, 2) carries three arguments. Only the version with three parameters fits, and it returns 10. In the output the first and the third lines are both 10, but they come from different methods.
The fourth call is sum('A', 1); the arguments are (char, int). In Java the type char holds the numeric code of a character and can widen to both int and double. Both versions are applicable; the compiler chooses the most specific, (int, int). Since the code of the character 'A' is 65, the method runs with a = 65, b = 1 and returns 66. What appears on the screen is not a letter but the number 66.
The consequences of the widening chain are sometimes surprising. In the following program the print method has int, long and double versions; each version prints a different letter.
public class Print {
static void print(int a) {
System.out.print("I");
}
static void print(long a) {
System.out.print("L");
}
static void print(double a) {
System.out.print("D");
}
public static void main(String[] args) {
print(5); print(5L);
print(5.0f); print('A');
System.out.println();
byte b = 3; short s = 4;
print(b); print(s); print(5_000_000_000L);
System.out.println();
}
}ILDI
IILprint(5) is an exact match: I. The suffix L in print(5L) makes the number a long: L. The suffix f in print(5.0f) makes the number a float. There is no float version; in the chain float can widen only to double: D. In print('A'), char can widen to int, long and double; the most specific is int: I. On the second line the byte and short arguments go to the nearest version, int: I I. 5_000_000_000L is a long beyond the range of int: L. The underscores in the number are only for readability; they do not change the value.
There are also cases in which no most specific method exists. If neither of two applicable methods is more specific than the other, the compiler makes no choice and rejects the call:
public class Ambiguous {
static void g(int a, double b) { }
static void g(double a, int b) { }
public static void main(String[] args) {
g(1, 1);
}
}Ambiguous.java:5: error: reference to g is ambiguous
g(1, 1);
^
both method g(int,double) in Ambiguous and method g(double,int) in Ambiguous match
1 errorIn the call g(1, 1) both versions are applicable: in the first the second argument is widened to double, in the second the first argument is. Between (int, double) and (double, int) neither can widen to the other; neither is “more specific”. The call is ambiguous, as the message says. If the call is written as g(1, 1.0), the ambiguity disappears. This error shows why merely changing the order of the parameter types is not a good idea in overloading.
3.2.7Methods calling methods
Methods are not called only from main; a method can also call another method. This is how a large task is split into small pieces. Each piece does its own job and hands its result to a higher level.
3.2.7.1Methods that call each other
In the following program, the sumOfSquares method, which finds the sum of the squares of two numbers, does not do the work itself. It has square do the squaring and sum do the adding.
public class Nested {
public static int square(int num) {
return num * num;
}
public static int sum(int num1, int num2) {
return num1 + num2;
}
public static int sumOfSquares(int num1, int num2) {
return sum(square(num1), square(num2));
}
public static void main(String[] args) {
int result = sumOfSquares(3, 4);
System.out.println(result);
}
}25The result of the call sumOfSquares(3, 4) is 3² + 4² = 9 + 16 = 25. The key line of the code is return sum(square(num1), square(num2));. In this line the arguments of one call are other calls. Java evaluates such an expression from the inside out. Before sum can be called, the values of its two arguments must be known; so square(num1) runs first, then square(num2). When both results are ready, sum(9, 16) is called.
The order in which arguments are evaluated is precisely defined in Java: left to right. This rule matters when one of the arguments prints something or changes a variable. In the following program the value method both returns a value and prints its own name, so the order of the calls shows up in the output.
public class Order {
static int value(String name, int v) {
System.out.print(name + " ");
return v;
}
static int diff(int a, int b) {
return a - b;
}
public static void main(String[] args) {
int s = diff(value("left", 10), value("right", 3));
System.out.println("→ " + s);
}
}left right → 7First left and then right is printed. Then diff(10, 3) runs and returns 7. Some languages, such as C, do not specify this order and leave it to the compiler. Java guarantees the order.
Having methods call each other makes the program readable and manageable. The body of sumOfSquares says in one line what it does: the sum of two squares. square and sum can be tested separately. If square works wrongly, the bug is fixed in one place and all the methods that use it are fixed.
3.2.7.2Tracing the call stack
With nested calls the call stack has several levels. Table 3.2.7 gives the execution of the program step by step.
| Step | Line | Call stack | Variables | Output |
|---|---|---|---|---|
| 1 | 12: int result = sumOfSquares(3, 4); | main() | result=? | — |
| 2 | 9: return sum(square(num1), square(num2)); | main() → sumOfSquares(3, 4) | num1=3, num2=4 | — |
| 3 | 2: return num * num; | main() → sumOfSquares(3, 4) → square(3) | num=3, return=9 | — |
| 4 | 9: return sum(square(num1), square(num2)); | main() → sumOfSquares(3, 4) | num1=3, num2=4, arg1=9 | — |
| 5 | 2: return num * num; | main() → sumOfSquares(3, 4) → square(4) | num=4, return=16 | — |
| 6 | 5: return num1 + num2; | main() → sumOfSquares(3, 4) → sum(9, 16) | num1=9, num2=16, return=25 | — |
| 7 | 9: return sum(square(num1), square(num2)); | main() → sumOfSquares(3, 4) | num1=3, num2=4, return=25 | — |
| 8 | 12: int result = sumOfSquares(3, 4); | main() | result=25 | — |
| 9 | 13: System.out.println(result); | main() | result=25 | 25 |
In the first step main calls sumOfSquares(3, 4); there are two frames on the stack. In the second step sumOfSquares starts evaluating its arguments before calling sum. In the third step a third frame is opened for square(3); 3 × 3 = 9 is returned. The first part of Figure 3.2.7 shows this moment.
square(3) is running, with sumOfSquares(3, 4) and main waiting below it. On the right sum(9, 16) is running; its own num1 is 9, while the num1 of sumOfSquares below it is still 3.In the fourth step the frame of square is closed. The first argument is now known: 9. In the fifth step a new frame is opened for square(4) and 16 is returned. This frame is not a reuse of the earlier square frame; it is a separate frame opened for a new call of the same method. Every call carries its own parameters and local variables.
In the sixth step the arguments are ready and sum(9, 16) is called. The parameters of sum are also named num1 and num2. In the frame of sum, num1 = 9; at the same time, in the sumOfSquares frame one level down the stack, num1 = 3. The two variables do not affect each other. In the seventh step the 25 returned by sum also becomes the return value of sumOfSquares. In the eighth step control returns to main and result = 25. In the ninth step 25 is printed.
During the trace there were at most three frames on the stack at the same time: main, sumOfSquares and the helper method running at that moment. The depth of the stack equals the longest chain of nested calls. square and sum were never on the stack at the same time, because neither started before the other had finished.
It is also worth knowing that the stack is not unlimited. Every frame takes up memory. If a method calls itself endlessly, the frames pile up and the stack fills; the program stops with a StackOverflowError. Methods that call themselves are called recursive methods; for such methods the depth of the stack must be checked separately.
3.2.8Built-in methods
Not every programmer writes every job from scratch. Java comes with a standard library of thousands of classes and methods. There are ready-made methods for taking square roots, printing with formatting, sorting arrays and reading files. Using these methods is no different from using the methods we write ourselves: their names, parameters and return types are known, and their insides are not.
3.2.8.1The Java library and packages
The standard library of Java is called the Java API (Application Programming Interface). The classes in the library are divided into packages. A package is a namespace that groups related classes together. Table 3.2.8 lists the most commonly used classes and their packages.
| Area | Classes | Example methods | Package |
|---|---|---|---|
| Printing | System.out | print, println, printf | java.lang |
| Mathematics | Math | sqrt, abs, max, pow | java.lang |
| Text | String | length, charAt, substring, equals | java.lang |
| Arrays | Arrays | sort, copyOf, binarySearch, equals | java.util |
| User input | Scanner | nextInt, nextLine, close | java.util |
| Files | File, FileWriter | createNewFile, write, close | java.io |
| Database | DriverManager, Statement | getConnection, executeQuery, executeUpdate | java.sql |
| Data structures | ArrayList | add, remove, get, size | java.util |
| Time | LocalDateTime, DateTimeFormatter | now, ofPattern, format | java.time |
| Web / graphics | URI, URL, JFrame | URI.create, openConnection, setVisible | java.net, javax.swing |
The java.lang package is special: it is included in every Java program automatically. Since System, Math and String are in this package, they are used without any preparation. For classes in other packages an import declaration is written at the top of the file: import java.util.Scanner;. If this declaration is left out, the compiler does not recognize the name Scanner and says cannot find symbol.
Some of the methods in the table are static and are called with the class name: Math.sqrt(16), Arrays.sort(arr). Others are called through an object: in.nextInt(), text.length(). Which form a method is called in is stated in the header of the method in the official Java documentation.
3.2.8.2Printing to the screen
System.out is a ready-made object that represents standard output, that is, the console. Three of its methods are used very often.
public class Printing {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.print("One ");
System.out.print("line");
System.out.println();
int age = 20;
System.out.println("Age: " + age);
System.out.printf("Pi is about %.2f%n", Math.PI);
}
}Hello, World!
One line
Age: 20
Pi is about 3.14System.out.println(x)printsxand moves to the next line.println()without an argument prints only a line break.System.out.print(x)printsxbut stays on the same line. In the programprint("One ")andprint("line")run one after the other, and thenprintln()ends the line:One line.System.out.printf(format, values...)prints with formatting. The values are put in place of the placeholders in the format string.
Text and a value are joined with the + operator: the value of the expression "Age: " + age is the string "Age: 20". Because the + operator works from left to right, the order of concatenation changes the result. This detail is a point where beginners often get stuck:
import java.util.Locale;
public class Format {
public static void main(String[] args) {
double avg = 81.66666666666667;
System.out.printf("%.2f%n", avg);
System.out.printf(Locale.US, "%.2f%n", avg);
System.out.printf("%d students, average %.1f, grade %s%n", 3, avg, "BB");
System.out.printf("[%5d] [%-5d] [%05d]%n", 42, 42, 42);
System.out.println(1 + 2 + " total");
System.out.println("total " + 1 + 2);
System.out.println("total " + (1 + 2));
System.out.println(String.format("%.3f", Math.PI));
}
}81,67
81.67
3 students, average 81,7, grade BB
[ 42] [42 ] [00042]
3 total
total 12
total 3
3,142In the expression 1 + 2 + " total", 1 + 2 is first the sum of two numbers: 3. Then 3 is appended to the text: 3 total. In "total " + 1 + 2, however, the first operation is the concatenation of a string with a number: "total 1". Since the result is now a string, the 2 is also appended to the text: total 12. To compute the sum as a number, parentheses are needed: "total " + (1 + 2).
The placeholders most often used in printf are given in Table 3.2.9.
| Placeholder | Meaning | Example | Output |
|---|---|---|---|
%d | integer | printf("%d", 42) | 42 |
%.2f | decimal number, 2 digits | printf("%.2f", Math.PI) | 3.14 |
%s | text | printf("%s", "BB") | BB |
%n | line break | printf("a%nb") | two lines |
%5d / %-5d | right / left aligned in a field of 5 characters | printf("[%5d]", 42) | [ 42] |
%05d | pad with zeros instead of spaces | printf("[%05d]", 42) | [00042] |
When printf prints a decimal number, it uses the computer's locale. On a system set to Turkish the decimal separator is a comma, so Math.PI is printed as 3,14. println, on the other hand, ignores the locale and always uses a point: 3.141592653589793. If a program prints the same number in the two ways, two different forms appear. If the decimal separator should be a point on every system, the locale is given explicitly: the output of printf(Locale.US, "%.2f%n", avg) is 81.67. The Locale class is in the java.util package and has to be imported.
The placeholder %.2f rounds the number rather than truncating it: the value 81.666… becomes 81,67. String.format uses the same format rules as printf, but instead of printing the result it returns it as a string. The 3,142 on the last line comes from this method.
3.2.8.3The Math class
The Math class contains ready-made methods for mathematical operations. All of its methods are static; so no Math object is created, and the methods are called with the class name.
double root = Math.sqrt(16);
double absValue = Math.abs(-17.2);
double maximum = Math.max(3, 5);
System.out.println(root);
System.out.println(absValue);
System.out.println(maximum);
System.out.println(Math.pow(2, 10));
System.out.println(Math.round(2.6));
System.out.println(Math.min(-4, 7));
System.out.println(Math.max(3, 5));4.0
17.2
5.0
1024.0
3
-4
5The form of each line in the output reveals the return type of the method. Table 3.2.10 lists these methods together with their return types.
| Method | Role | Return type | Example → result |
|---|---|---|---|
sqrt(x) | square root | always double | Math.sqrt(16) → 4.0 |
pow(a, b) | a to the power b | always double | Math.pow(2, 10) → 1024.0 |
abs(x) | absolute value | type of the argument | Math.abs(-17.2) → 17.2 |
max(a, b), min(a, b) | the larger / the smaller | common type of the arguments | Math.max(3, 5) → 5 |
round(x) | rounds to the nearest integer | long for double | Math.round(2.6) → 3 |
floor(x), ceil(x) | rounds down / up | double | Math.floor(-2.5) → -3.0 |
PI | the constant π (not a method) | double | Math.PI → 3.141592653589793 |
abs, max and min are overloaded; different versions run depending on the type of the argument. Math.max(3, 5) takes two ints and returns an int: 5. When the result of the same call is assigned to a double variable in a program, it is widened to 5.0 and 5.0 is printed. sqrt and pow, on the other hand, have only a double version; even if an integer argument is given, the result is a double. Assigning the result directly to an int variable is therefore a compile error:
public class SqrtInt {
public static void main(String[] args) {
int k = Math.sqrt(16);
}
}SqrtInt.java:3: error: incompatible types: possible lossy conversion from double to int
int k = Math.sqrt(16);
^
1 errorIf the result is needed as an integer, an explicit cast is written: int k = (int) Math.sqrt(16);. The (int) cast truncates the fractional part; it does not round. In expressions where return types are mixed, the result must be followed carefully. The following program gives a few more examples.
public class MathExtras {
public static void main(String[] args) {
System.out.println(Math.round(2.5) + " " + Math.round(-2.5) + " " + Math.round(-2.6));
System.out.println(Math.floor(-2.5) + " " + Math.ceil(-2.5));
System.out.println(Math.sqrt(-4));
System.out.println((int) Math.pow(2, 10));
System.out.println(Math.max(Math.abs(-8), Math.sqrt(49)));
System.out.println(Math.sqrt(16) + Math.max(3, 7) / 2);
System.out.println(Math.PI);
System.out.println(Math.hypot(3, 4));
long r = Math.round(2.6);
System.out.println(r);
}
}3 -2 -3
-3.0 -2.0
NaN
1024
8.0
7.0
3.141592653589793
5.0
3The first line shows the behavior of Math.round. The method adds 0.5 to the number and rounds down. For 2.5 the result is 3; for −2.5, −2.5 + 0.5 = −2. So halves are always rounded toward positive infinity; −2.6, however, becomes −3. On the second line floor rounds −2.5 down to −3.0, and ceil rounds it up to −2.0. The square root of a negative number is undefined over the real numbers. Math.sqrt(-4) does not raise an error; it returns the special value NaN (Not a Number).
In the expression Math.max(Math.abs(-8), Math.sqrt(49)) on the fifth line, the inner calls run first. Math.abs(-8) gives an int: 8. Math.sqrt(49) gives a double: 7.0. Because the arguments of max are (int, double), the overloading rules come into play and the version max(double, double) is chosen. The result is 8.0, not 8.
In the expression Math.sqrt(16) + Math.max(3, 7) / 2 on the sixth line, operator precedence matters. The division is done before the addition. Math.max(3, 7) returns an int: 7. 7 / 2 is an integer division: 3. Then 4.0 + 3 is computed and the result is 7.0. Math.hypot(3, 4) gives the hypotenuse of the triangle whose legs are 3 and 4: 5.0.
3.2.9Scope
A variable cannot be used everywhere in a program. Where it is defined determines where it can be seen and how long it lives. These rules let methods work independently of each other: variable names inside one method do not get mixed up with names in other methods.
3.2.9.1Local variables
A local variable is a variable defined inside a method or a block that is valid only there. The parameters of a method are also local variables. A local variable exists only while the method is running; when the method returns, it is removed.
In the following code the multiply method uses a local variable named result. After calling multiply, otherMethod tries to reach this variable.
public int multiply(int num1, int num2) {
int result = num1 * num2; // 'result' is a local variable
return result;
}
public void otherMethod() {
multiply(2, 3);
System.out.println(result); // ERROR
}LocalOutside.java:8: error: cannot find symbol
System.out.println(result); // ERROR
^
symbol: variable result
location: class LocalOutside
1 errorThe compiler cannot find the name result inside otherMethod. result belongs to multiply and exists only while multiply is running. Figure 3.2.8 shows this in memory: while multiply(2, 3) runs, its frame holds num1, num2 and result. When the method returns, the frame and the variables in it are removed.
multiply(2, 3) runs, its frame is on top of the stack: num1 = 2, num2 = 3, result = 6. On the right the method has returned; the frame is gone and only otherMethod is left below.The way to carry the value out of the method is again return. If int s = multiply(2, 3); is written inside otherMethod, the returned 6 is assigned to s, a local variable of otherMethod itself. In the code that causes the compile error, on the other hand, the line multiply(2, 3); assigns the result nowhere, so the 6 is lost.
Local variables have one more rule: they must be given a value before they are used. Class fields and array elements have default values (0, false, null); local variables do not. Reading a local variable that has not been given a value is a compile error:
public class UninitializedLocal {
public static void main(String[] args) {
int t;
System.out.print(t);
}
}UninitializedLocal.java:4: error: variable t might grade have been initialized
System.out.print(t);
^
1 error3.2.9.2Scope rules and nested blocks
The scope of a variable is the region of the program in which its name is valid. In Java the scope of a local variable begins at the line where it is declared and ends at the end of the braced block in which it is declared.
Scope determines two things: where the variable can be accessed and how long it will live. In Java, blocks can be nested. The body of the class is the outermost block. The methods are inside it. Inside the methods there can in turn be if blocks, loops, or blocks written as plain braces. Figure 3.2.9 shows these layers.
globalVar; inside it the method scope with outerVar; innermost the block scope with innerVar. The innermost block sees all the variables outside it.The rule is one-way: an inner scope sees the variables of the outer scope; an outer scope cannot see the variables inside. In the following program the inner block reaches the variables of both the method and the class.
public class InnerScope {
static int globalVar = 10; // global (class field)
static void method() {
int outerVar = 10; // local scope
{
int innerVar = 5;
// outerVar and innerVar are accessible here
System.out.println(outerVar + innerVar
+ globalVar);
}
// innerVar does NOT exist here
}
public static void main(String[] args) {
method();
}
}25The println in the inner block sees all three variables: innerVar is in its own block, outerVar in an outer block, and globalVar in the class scope. The total is 10 + 5 + 10 = 25. After the closing brace of the block, innerVar no longer exists. If innerVar is used there, the compiler says cannot find symbol.
globalVar, defined in the class body outside the methods, is a field. All methods of the class see this field. What programming languages call a “global variable”, one that is accessible everywhere and lives for the whole program, corresponds in Java to static fields. In Java a variable cannot be defined outside a class; there is no truly global variable.
| Scope | Where is it defined? | Where can it be accessed? | How long does it live? |
|---|---|---|---|
| Local (block) | Inside a block | From the line where it is defined to the end of the block | As long as the block runs |
| Local (method) | In the method body or the parameter list | From inside the method | As long as the method runs |
static field | In the class body, outside the methods | From all methods of the class | For the whole program |
Loop variables obey this rule too. The scope of i, defined in the header for (int i = 0; ...), is the loop itself. Using i after the loop has ended is a compile error:
public class OutsideLoop {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) { }
System.out.print(i);
}
}OutsideLoop.java:4: error: cannot find symbol
System.out.print(i);
^
symbol: variable i
location: class OutsideLoop
1 errorA benefit of limited scope is that the same name can be reused in blocks that cannot see each other. Two sibling blocks, that is, blocks where one ends before the other begins, can define variables with the same name without confusion. That is why it is valid to use i in two for loops written one after the other:
public class SiblingBlocks {
public static void main(String[] args) {
{ int t = 1; System.out.print(t + " "); }
{ int t = 2; System.out.println(t); }
for (int i = 0; i < 2; i++) { int square = i * i; System.out.print(square + " "); }
for (int i = 5; i < 7; i++) { System.out.print(i + " "); }
System.out.println();
}
}1 2
0 1 5 6 3.2.9.3Name clashes and shadowing
Using the same name in different scopes has two different consequences. Java forbids one of them and allows the other.
The forbidden case: an inner block cannot use the same name as a local variable in an outer block. Since both variables would live at the same time and carry the same name, it would be unclear which one is meant. Java does not allow this ambiguity:
public void method() {
int outerVar = 10;
{
int outerVar = 5; // ERROR
}
}SameName.java:5: error: variable outerVar is already defined in method method()
int outerVar = 5; // ERROR
^
1 errorThe same rule applies to parameters, because parameters are also local variables. A variable with the same name as a parameter cannot be defined in the body of the method:
public class SameNameParam {
static int f(int x) {
int x = 3;
return x;
}
}SameNameParam.java:3: error: variable x is already defined in method f(int)
int x = 3;
^
1 errorThe allowed case: a local variable may have the same name as a field of the class. In this case the local variable shadows the field.
Shadowing is when a name in an inner scope hides the same name in an outer scope. When a local variable shadows a field, the name refers to the local variable within that scope. The shadowed static field can be reached with the class name: ClassName.area.
public class Shadow {
static int value = 10; // class field
static void show() {
int value = 5; // shadows the field
System.out.println(value);
System.out.println(Shadow.value);
}
public static void main(String[] args) {
show();
System.out.println(value);
}
}5
10
10When Java sees a name, it first looks in the innermost scope and, if it does not find it, moves out to the next scope. Inside show, the name value is found in the local variable and 5 is printed. The notation Shadow.value, on the other hand, directs the search straight to the field of the class, and 10 is printed. In main there is no local variable named value; the search moves out to the class scope and the field is found: 10. Table 3.2.12 traces these steps.
| Step | Line | Call stack | Variables | Output |
|---|---|---|---|---|
| 1 | 9: show(); | main() | Shadow.value=10 | — |
| 2 | 3: static void show() { | main() → show() | Shadow.value=10 | — |
| 3 | 4: int value = 5; // shadows the field | main() → show() | Shadow.value=10, value (local)=5 | — |
| 4 | 5: System.out.println(value); | main() → show() | Shadow.value=10, value (local)=5 | 5 |
| 5 | 6: System.out.println(Shadow.value); | main() → show() | Shadow.value=10, value (local)=5 | 10 |
| 6 | 10: System.out.println(value); | main() | Shadow.value=10 | 10 |
Shadow.value = 10 lives outside the stack, for the whole program. In the frame of show there is a local value = 5 with the same name; inside the method the name value refers to this local variable.Shadowing does not cause a compile error, but it can lead to insidious bugs. A programmer may think they are changing the field while actually changing a local copy. There is also a common place where shadowing is used deliberately: when working with objects, in constructors and set methods the parameter has the same name as the field, and the field is reached with this.area.
3.2.9.4Lifetime
Scope says where a variable is visible; lifetime says when it exists. Local variables are born when their block is entered and die when the block is left. static fields are created once when the program starts and live until the program ends. The following program uses both kinds of variable together.
static int callCount = 0; // class field
static int multiply(int num1, int num2) {
callCount++;
int result = num1 * num2;
return result;
}
public static void main(String[] args) {
int first = multiply(2, 3);
{
int second = multiply(first, 4);
System.out.println(second);
}
System.out.println(first + " " + callCount);
}24
6 2| Step | Line | Call stack | Variables | callCount | Output |
|---|---|---|---|---|---|
| 1 | 8: int first = multiply(2, 3); | main() | first=? | 0 | — |
| 2 | 3: callCount++; | main() → multiply(2, 3) | num1=2, num2=3 | 1 | — |
| 3 | 4: int result = num1 * num2; | main() → multiply(2, 3) | num1=2, num2=3, result=6 | 1 | — |
| 4 | 8: int first = multiply(2, 3); | main() | first=6 | 1 | — |
| 5 | 4: int result = num1 * num2; | main() → multiply(6, 4) | num1=6, num2=4, result=24 | 2 | — |
| 6 | 10: int second = multiply(first, 4); | main() | first=6, second=24 | 2 | — |
| 7 | 11: System.out.println(second); | main() | first=6, second=24 | 2 | 24 |
| 8 | 13: System.out.println(first + " " + callCount); | main() | first=6 | 2 | 6 2 |
When the program starts, the field callCount is created and gets the value 0. In the first step multiply(2, 3) is called. In the second step the method increases the class field by 1. Methods can reach the class field because the field is in class scope. In the third step the local result is born and becomes 6. In the fourth step the method returns; num1, num2 and result disappear. The returned 6 is assigned to first, a local variable of main.
In the fifth step multiply(first, 4) is called from inside the inner block. In the new frame result = 24 and the field rises to 2. This result is not the result of the first call; the result of the first call was removed long ago. In the sixth step second is born. Because second is defined in the inner block, it lives only in that block. Figure 3.2.11 shows this moment.
main there are first = 6 and second = 24; the class field callCount = 2 is in a separate region. On the right the block has ended: second has disappeared, while first and the field live on.In the seventh step second is printed inside the block: 24. In the eighth step the block has ended and second no longer exists. first, however, lives until main ends. The last line prints 6 2: first is 6 and multiply has been called twice.
It is worth noticing that in this example a class field is used as a “counter”. A local variable could not do this job: a counter defined inside multiply is born anew on every call and starts from 0. Information that has to be kept between calls is held not in a local variable but in a field. Even so, fields should be used with moderation. A field that every method can change makes the behavior of the program hard to follow.
3.2.10Abstraction and design
Getting a method to compile and run correctly is half the job. The other half is designing the method well: how much work it does, which inputs it takes, and what it is called. Well-designed methods get reused in other programs, are easy to test, and can still be understood years later. This section covers the ideas that design rests on, namely abstraction, generalization and decomposition, followed by practical principles.
3.2.10.1Abstraction and the black box
Abstraction means hiding the details and showing only the important features in order to reduce complexity.
Abstraction is everywhere in daily life. To drive a car you do not need to know what is inside the engine. The steering wheel, the pedals and the gear lever are an interface through which the driver talks to the car. Even if the engine changes, for example when an electric motor replaces a petrol engine, the driver uses the same steering wheel and the same pedals.
Methods are a kind of abstraction as well. In Figure 3.2.12 Math.sqrt is drawn as a black box. The user gives the box 16 and gets 4.0. How the square root is computed inside the box is hidden and does not concern the user.
Math.sqrt computes the result is a hidden detail.Abstraction has two benefits. First, it makes the program understandable. A large program is split into pieces that can each be thought about separately; whoever uses a piece does not have to know its inside. Second, it makes change easier. When the inside of a method changes, the code that uses it is not affected as long as what the method does stays the same.
This kind of abstraction over computations is called functional abstraction or procedural abstraction. The basic idea is that what a function computes matters more than how it computes it. The user knows only the signature and the purpose of the method:
// The user knows only the signature:
static boolean isPrime(int num)
// "returns true if num is prime"
if (isPrime(17)) { ... }isPrime as a black box. 17 goes in and true comes out. The body is hidden; the user knows only the input and the output.All a programmer who writes the call isPrime(17) needs to know is that the method returns, as a boolean, whether a number is prime. Does the method divide the number by every number starting from 2, or does it try only up to the square root? This question is irrelevant to the user of the method. If a faster algorithm is written tomorrow, only the body of isPrime changes; the line if (isPrime(17)) stays exactly as it is.
The simplest example is again System.out.println("Hello"). This method writes the given text to the console. Details such as which encoding the characters are sent in, or which operating system call is used, are hidden from the programmer. Without abstraction, one would need to know all these details just to print a single line to the screen.
For abstraction to work, the purpose of the method must be clear. Since the user will not look at the body, the name, parameters and return type of the method must tell fully what it does. The header isPrime(int num) does this. The header process2(int a), on the other hand, tells nothing; the user has to read the body, and the abstraction collapses.
3.2.10.2Generalization
The meaning of a piece of code depends on its surroundings. The value of a number is related to the other terms in an equation, and the meaning of a word to its place in a sentence. In code, too, what a statement does depends on which variables hold which values in the block it is in. These surroundings are called the context.
Generalization means making a solution that belongs to one context usable in other contexts too. In code the tool of generalization is the parameter: constant values embedded in the solution are turned into parameters.
public class Generalization {
// Specific: prints exactly 10 '-' characters
static void drawLine() {
System.out.println("----------");
}
// General: length and character are parameters
static void drawLine(int length, char ch) {
for (int i = 0; i < length; i++) {
System.out.print(ch);
}
System.out.println();
}
public static void main(String[] args) {
drawLine();
drawLine(5, '*');
drawLine(12, '=');
}
}----------
*****
============The parameterless drawLine does only one thing: it prints ten dashes. The length and the character are embedded in the method. When a line of five stars is needed, this method is of no use; a new method has to be written. The version with two parameters generalizes the same job. The embedded number 10 has become the parameter length, and the embedded character '-' has become the parameter ch. Now a single method draws a line of any length with any character: drawLine(5, '*') prints five stars and drawLine(12, '=') prints twelve equals signs.
The two methods in the example have the same name; this is an example of overloading. The specific version could also have been written in terms of the general one: its body would be the one-line call drawLine(10, '-');. That way the logic of drawing a line stays in one place.
Generalization has a limit. Turning every constant into a parameter makes the method unusable. Calling a method with ten parameters can be harder than doing the job by hand. Generalization is limited to the values that are really expected to change.
3.2.10.3Decomposition
Decomposition means splitting a large problem into small, independent subproblems. In programming each subproblem becomes a method.
Consider a program that reads three grades of a student and prints the average and the letter grade. The problem splits into three subtasks: reading the grades, computing the average, and finding the letter grade from the average. Figure 3.2.14 shows this structure.
main calls three submethods: readGrades (input), computeAverage (process) and letterGrade (decision).In the following program all four methods are written out in full. The thresholds in letterGrade are chosen according to a common letter-grade table; a different table requires changing only this method.
import java.util.Scanner;
public class GradeProgram {
// readGrades and letterGrade are separate methods too
static int[] readGrades(Scanner in, int n) {
int[] grades = new int[n];
for (int i = 0; i < n; i++) {
grades[i] = in.nextInt();
}
return grades;
}
static double computeAverage(int[] grades) {
int sum = 0;
for (int n : grades) {
sum += n;
}
return (double) sum / grades.length;
}
static String letterGrade(double avg) {
if (avg >= 90) return "AA";
if (avg >= 85) return "BA";
if (avg >= 80) return "BB";
if (avg >= 75) return "CB";
if (avg >= 70) return "CC";
if (avg >= 60) return "DC";
if (avg >= 50) return "DD";
return "FF";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] grades = readGrades(in, 3);
double avg = computeAverage(grades);
System.out.println("Average: " + avg + " -> " + letterGrade(avg));
}
}The program was run with two different inputs:
Average: 81.66666666666667 -> BBAverage: 52.333333333333336 -> DDEach method does a single job. readGrades takes the Scanner object and the number of grades to read as parameters, and returns the grades it read as an array. The Scanner object is created once in main and passed to the method; this way the reading method does not have to know where the input comes from. computeAverage takes the array and returns the average. The explicit cast in the expression (double) sum / grades.length prevents integer division. 80 + 90 + 75 = 245; 245 / 3 would be 81 with integer division and 81.666… with floating-point division. letterGrade looks at the average and returns a String. The early-return pattern here takes the place of an else if chain: the conditions are tried from top to bottom, and the method ends at the first one that holds.
main now reads like a table of contents: read, compute, print. What is done is visible in main; how it is done is in the submethods. When a bug appears, it is also clear which method to look at. If the average is wrong, look at computeAverage; if the letter grade is wrong, look at letterGrade.
Another benefit of decomposition is that the methods can be tested separately. letterGrade can be tested without touching the keyboard at all: letterGrade(85) should return “BA” and letterGrade(84.99) should return “BB”. If reading and computing had been written intertwined, every test would require typing grades at the keyboard.
3.2.10.4When to write a method: the DRY principle
The clearest sign that a piece of code should be a method is repetition. The name of this principle is DRY (Don't Repeat Yourself). The moment you feel the need to copy and paste code, that code is a candidate to become a method.
The first fragment below is the repetitive version and the second is the version with a method. Both print the average of two students.
double avg1 = (70 + 80 + 90) / 3.0;
System.out.println(avg1);
double avg2 = (55 + 60 + 100) / 3.0;
System.out.println(avg2);
// if the formula changes, it has to be
// fixed separately in every placestatic double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
System.out.println(average(70, 80, 90));
System.out.println(average(55, 60, 100));80.0
71.66666666666667
80.0
71.66666666666667In the repetitive version the average formula is written twice. If the formula changes, for example if the grades are to be weighted differently, both places have to be fixed separately. In real programs the same formula can appear in dozens of places, and forgetting one is easy. In the version with a method the formula is in one place: the body of the average method. The change is made once and shows up in every call.
The value 71.66666666666667 in the output comes from the limited precision of double. 215 / 3 = 71.666… has an infinite decimal expansion. double stores it with about 16 significant digits and the last digit is rounded. In a result to be shown to a user, the number of digits is limited with printf("%.2f", ...).
Repetition is not the only criterion. A piece of code that is used only once can also deserve to be a method. There are two reasons: the piece does a meaningful job on its own, or gathering it under a name makes the calling code readable. letterGrade in the grade program is called only once, but being a separate method simplifies main and makes testing easier.
3.2.10.5Designing good methods
The properties of a good method can be gathered into six principles.
- Single responsibility
- Each method does only one job. If the task of a method is described with the word “and” (read and compute and print), the method should be split.
- Descriptive name
- The name of a method is a verb that tells what it does:
computeAverage,isPrime,readGrades. Names such asprocess2say nothing. - Parameters
- A method takes the data it needs through parameters; it does not secretly depend on outside variables. A small number of parameters improves readability.
- Return value
- The result is returned explicitly with
return. A method that computes does not print; printing is done by the caller. - Short and focused
- Methods of a few lines that fit on one screen are easy to understand and easy to test.
- Called where needed
- A method is called only where it is needed. Computing the same result again and again in a loop is wasted work; the result is computed once and kept in a variable.
The principle “a method that computes does not print” is the one most often broken. The design that first comes to a student's mind is usually this:
static void computeAndPrintAverage(int a, int b, int c) {
System.out.println((a + b + c) / 3.0);
}This method can only print the average to the screen. Code that wants to test whether the average is greater than 50, save the average to a file, or include it in the class average cannot use it; the result has stayed on the screen. A better design is to return the average and let the caller decide what to do:
static double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
// the caller decides:
System.out.println(average(70, 80, 90));
if (average(40, 50, 45) < 50) System.out.println("failed");The principle “do not secretly depend on outside variables” rests on the same reasoning. A method that reads its values from class fields depends on the current values of the fields. To understand what the method will return, you have to know where in the rest of the program the fields are changed. The result of a method that takes parameters, on the other hand, depends only on its arguments; with the same arguments it gives the same result every time.
3.2.10.6Naming
Choosing good names applies not only to methods but also to variables. Each variable should represent one thing. Using the same variable first for an age and then for a total confuses the reader and leads to logic errors. The name of a variable should tell what kind of data it holds.
int studentCount; // a good name
int a; // a meaningless name
int age = 25;
String name = "Ahmet";
double average = 85.5;
String bookTitle;Meaningless or single-letter names reduce readability. There are two exceptions: conventional names such as i and j as loop counters, and x and y in mathematical formulas. Table 3.2.14 compares a few bad names with better ones.
| Bad | Good | Why? |
|---|---|---|
int x1, x2; | int midtermGrade, finalGrade; | The name tells which grade is which. |
double d; | double circleArea; | It is clear what the variable holds the value of. |
boolean f; | boolean isPrime; | if (isPrime) reads like a question. |
Java's writing conventions also reveal the kind of a name. Variable and method names are written in camelCase and start with a lowercase letter: studentCount, readGrades. Class names start with an uppercase letter: Book, Scanner. Constants that never change are written in uppercase letters with underscores: MAX_VALUE. These conventions are not required by the compiler, but they are universal among Java programmers. A reader who sees a name immediately understands whether it is a variable, a class or a constant.
Using non-ASCII characters, such as Turkish letters, in variable and method names is technically allowed in Java: int öğrenciSayısı; compiles. But problems arise when the encoding of the file and the encoding the compiler expects do not match. For this reason, in courses and in most projects names are written with the letters of the English alphabet: studentCount.
3.2.11Worked problems
The following problems use method calls, pass by value and overloading together. All solutions were run with Java.
What does the following program print? Why does a not change? How many frames are on the stack at most while cube(2) is running?
static int f(int x) {
x = x * 2;
return x + 1;
}
public static void main(String[] args) {
int a = 3;
int b = f(a);
System.out.println(a + " " + b);
System.out.println(f(f(1)));
}static int square(int n) { return n * n; }
static int cube(int n) { return n * square(n); }
// inside main:
System.out.println(cube(2) + square(3));3 7
7
17In the call f(a), the value of a, that is 3, is copied into the parameter x of f. x = x * 2 makes the copy 6, and x + 1, that is 7, is returned. b becomes 7. a does not change, because f changed only its copy: the first line is 3 7.
In the expression f(f(1)) the inner call runs first: f(1) = 1 × 2 + 1 = 3. The outer call runs with this value: f(3) = 3 × 2 + 1 = 7. The second line is 7.
In the expression cube(2) + square(3), cube(2) computes 2 * square(2). square(2) returns 4 and cube(2) becomes 8. Then square(3) = 9 is computed. The total is 8 + 9 = 17. While cube(2) runs, the deepest moment is when square(2) is running: there are 3 frames on the stack, main, cube(2) and square(2). When square(3) is called, the frame of cube has long been closed; at that moment there are only 2 frames on the stack.
Which sum method do the first two println calls invoke? Why does the last line print 8.0 and not 8?
static int sum(int a, int b) { return a + b; }
static double sum(double a, double b) { return a + b; }
// inside main:
System.out.println(sum(2, 3.0));
System.out.println(sum(2, 3));
System.out.println(Math.max(Math.abs(-8), Math.sqrt(49)));5.0
5
8.0The arguments of the call sum(2, 3.0) are (int, double). The (int, int) version does not fit, because 3.0 cannot be narrowed to int. The (double, double) version fits: the value 2 is widened to 2.0. The result is 5.0. In the call sum(2, 3) both versions are applicable; the most specific, (int, int), is chosen and 5 is printed. On the last line, because Math.sqrt returns double, the (double, double) version of Math.max is chosen. The larger of 8 and 7.0 is 8.0.
Let us write the following methods: isEven, which returns whether a number is even; largest, which finds the largest of three numbers with Math.max; power, which raises to a power without Math.pow; digitSum, which finds the sum of the digits; circleArea, which returns the area of a circle; and area, overloaded for a circle and a rectangle.
public class Exercises {
static boolean isEven(int num) {
return num % 2 == 0;
}
static int largest(int a, int b, int c) {
return Math.max(a, Math.max(b, c));
}
static int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) result *= base;
return result;
}
static int digitSum(int n) {
int t = 0;
while (n != 0) { t += n % 10; n /= 10; }
return t;
}
static double circleArea(double r) {
return Math.PI * r * r;
}
static double area(double r) {
return Math.PI * r * r;
}
static double area(double width, double height) {
return width * height;
}
public static void main(String[] args) {
System.out.println(isEven(7) + " " + isEven(10) + " " + isEven(-4));
System.out.println(largest(4, 9, 2));
System.out.println(power(2, 10) + " " + power(5, 0));
System.out.println(digitSum(2024) + " " + digitSum(-2024));
System.out.printf("%.2f%n", circleArea(2));
System.out.println(area(1) + " " + area(3, 4));
}
}false true true
9
1024 1
8 -8
12,57
3.141592653589793 12.0The body of isEven is a single line: return num % 2 == 0;. The result of the comparison is already a boolean; there is no need to write if (num % 2 == 0) return true; else return false;. It also works for negative numbers: -4 % 2 is 0.
largest calls Math.max in a nested way: first the larger of b and c is found, and then this value is compared with a. largest(4, 9, 2) returns 9. power uses an accumulator. result starts at 1 and is multiplied by base exp times. power(2, 10) returns 1024. In power(5, 0) the loop never runs and 1 is returned; this agrees with the rule 5⁰ = 1 in mathematics.
digitSum takes the last digit of the number with n % 10 and discards it with n /= 10. Table 3.2.15 traces the loop for 2024.
| Iteration | n % 10 | t (after) | n / 10 |
|---|---|---|---|
| 1 | 4 | 4 | 202 |
| 2 | 2 | 6 | 20 |
| 3 | 0 | 6 | 2 |
| 4 | 2 | 8 | 0 |
n = 0: the loop ends, return t; → 8 | |||
For negative numbers, since Java's remainder operation takes the sign of the dividend, digitSum(-2024) returns −8. If the digit sum should always be positive, n = Math.abs(n); is written at the start of the method.
circleArea(2) returns π × 2 × 2 ≈ 12.566. printf("%.2f%n", ...) rounds this to two digits; with the Turkish locale the output is 12,57. In the overloaded area methods, the number of arguments determines which version is called. area(1) runs the circle version and gives π: 3.141592653589793. area(3, 4) runs the rectangle version: 12.0. Because the integer arguments are widened to double parameters, the result is a double as well.
3.2.12Common mistakes
The compiler catches some mistakes with methods and points out their location in its message. Others produce programs that compile but give unexpected results. The second group is more dangerous, because the program runs wrongly without any warning.
Calling a non-static method from main. Message: non-static method add(int,int) cannot be referenced from a static context. Either static is added to the header of the method, or an object is created and the method is called through it.
Forgetting return on some paths. Message: missing return statement. The compiler does not reason about the values of conditions; a chain if (n > 0) ... if (n <= 0) ... gives an error even though it looks complete to a human. The last branch becomes a plain else, or a default return is put at the end of the method.
Using the result of a void method. The line int x = sayHello(); gives incompatible types: void cannot be converted to int, and println(sayHello()) gives 'void' type not allowed here. A void method produces no value; its call can only be a statement on its own.
Missing or extra arguments. Message: method add in class ... cannot be applied to given types; below it the lines required: int,int and found: int show the expected and the supplied types. The number, order and types of the arguments must match the signature.
Using a local variable outside its method. Message: cannot find symbol ... variable result. A local variable disappears when the method ends; its value is returned with return and the caller assigns it to its own variable.
The same name as an outer local variable in an inner block. Message: variable outerVar is already defined in method method(). The same rule applies to parameters. A local variable having the same name as a field, on the other hand, is allowed; then shadowing occurs.
Expecting a swap method to work. swap(int x, int y) swaps only copies; after the call swap(arr[0], arr[2]) the array stays the same. To swap array cells, the method takes the array and the indices: swap(int[] d, int i, int j).
Expecting an argument to change. After the call increase(num), num stays the same; what changed is the copy in the method. The new value is returned with return and assigned: num = increase(num);. The compiler gives no warning when the returned value is not assigned.
Overloading by return type. int f(int a) and double f(int a) cannot coexist: method f(int) is already defined. Only the name and the parameter types determine the signature; the return type and the parameter names are not part of it.
Forgetting the type of a Math result. The line int k = Math.sqrt(16); gives the message possible lossy conversion from double to int. sqrt and pow always return double; if an integer is needed, the (int) cast is written.
Expecting the return type to change the calculation. The method static double half(int n) { return n / 2; } returns 3.0 for 7. The division is done between two ints and the fraction is discarded; the double return type merely widens the result. The correct form is n / 2.0.
Printing inside a method that computes. The result of a method such as computeAndPrintAverage stays on the screen; it cannot be used in another calculation. The method returns the result, and the caller does the printing.
3.2.13Summary
- A function is a named piece of code that does one job and can be reused. In Java it is always written inside a class and is called a method. The input comes in through parameters, and the output comes back with
return. - Method header:
access [static] returnType name(parameters). Each parameter carries its own type. The signature is the name plus the sequence of parameter types; the return type is not part of it. Methods cannot be defined inside one another. - A parameter is the variable in the definition, and an argument is the value in the call. Arguments are evaluated first (left to right) and then copied into the parameters. The number, order and types must match.
- Every call opens a new frame on the call stack; the frame holds the parameters and local variables. When the method returns, the frame is removed. The depth of the stack equals the longest chain of nested calls.
returngives the value and ends the method at once; a statement after it cannot be reached. In a method that returns a value, every path must end in areturn; the compiler does not reason about the values of conditions. Avoidmethod returns no value and can exit early with a barereturn;.- The returned value can widen to the return type (
int→double) but cannot narrow. The return type does not change how an expression is evaluated. - A
staticmethod belongs to the class; it is called directly or withClassName.method(). A method that is notstaticis called through an object:object.method(). - Java passes arguments by value. Even if the copy of a primitive argument changes, the caller's variable does not. With an array argument the reference is copied: the method can change the shared array, but assigning a new array to the parameter does not affect the caller.
- Overloading: same name, different parameter list. The compiler makes the choice at compile time by looking at the argument types. An exact match is looked for first; if there is none, widening is tried (
byte → short → int → long → float → double,char → int). If several versions are applicable, the most specific is chosen; if there is no most specific version, the call is ambiguous. System.out.printlnadds a line break,printdoes not, andprintfprints with formatting and uses the locale for the decimal separator.+concatenation works from left to right.Mathmethods arestatic.sqrtandpowalways returndouble,abs/max/minreturn the type of the argument, andround(double)returnslong. Packages other thanjava.langneed animport.- A local variable lives in the block where it is defined and must be given a value before use. An inner scope sees the outside, and an outer scope cannot see the inside. An inner block cannot use the same name as an outer local; a local variable, however, shadows a field of the same name.
staticfields live for the whole program. - Design: abstraction (what it does matters, how it does it is hidden), generalization (constants become parameters), decomposition (each subtask becomes a method), DRY (repeated code goes into a method), single responsibility, descriptive names, returning the result and leaving the printing to the caller.
3.2.14Key terms
The key terms of this chapter are listed below.
- function
- method
- method call
- parameter
- argument
- return type
- return value
- method signature
- access modifier
- static member
- call stack
- stack frame
- pass by value
- reference
- heap
- method overloading
- widening / narrowing conversion
- import
- package
- locale
- local variable
- field
- scope
- shadowing
- garbage collector
- abstraction
- decomposition
3.2.15Test Yourself
The methods
static int a(int n) { return b(n + 1) * 2; },static int b(int n) { return c(n) + n; }andstatic int c(int n) { return n * n; }are given. Ifa(2)is called frommain, what is returned? What is the greatest number of frames on the stack at the same time?Answer
a(2)callsb(3).b(3)callsc(3), andc(3)returns 9.b(3)returns 9 + 3 = 12.a(2)returns 12 × 2 = 24. Whilec(3)runs, there are 4 frames on the stack,main,a,bandc; this is the deepest moment.The method
static int change(int[] d, int k) { d[k] = d[k] + k; k = 0; return d[k]; }is called inmainwithint[] d = {3, 4, 5}; int k = 2; int r = change(d, k);. What ared,kandrafter the call?Answer
The method's
dis a copy of the reference to the array inmain; itskis a copy of 2.d[2] = 5 + 2 = 7changes the shared array.k = 0changes only the copy.return d[0]returns 3. Result: the array is{3, 4, 7},kinmainis still 2, andr = 3.A class has the methods
m(long x),m(double x)andm(int x, int y); each returns its own parameter types as a string. After the declarationsshort s = 7; char ch = 'x';, which versions dom(s),m(ch),m(3.0f)andm(2, 'b')call?Answer
In the calls with one argument, the version with two parameters is eliminated because of the count.
shortcan widen to bothlonganddouble;longis more specific:m(s)→ long.charwidens first tointand from there tolong; againlongis chosen:m(ch)→ long.floatwidens only todouble: double. Inm(2, 'b'),'b'widens toint: int,int. JDK 21 output:long long double int,int.A class has the field
static int count = 0;and the methodstatic int increment(int count) { count++; TryIt.count += 2; return count; }. After the lineint t = increment(5);, what aretand the class fieldcount?Answer
The parameter
countshadows the field.count++makes the parameter 6; the field is not affected.TryIt.count += 2reaches the field through the class name and makes it 2. The method returns the parameter:t = 6. The field is 2.What does the method
static double ratio(int a, int b) { return a / b; }return forratio(7, 2)andratio(1, 3)? How is the method fixed?Answer
a / bis an integer division between twoints. 7 / 2 = 3 and 1 / 3 = 0; on the way out they are widened todouble:3.0and0.0. The return type does not change the calculation. Fix:return (double) a / b;. The results are then 3.5 and 0.333….Which of the following pairs of methods can exist together in the same class? (a)
void g(int x)andint g(int y); (b)int h(int a, double b)andint h(double a, int b); (c)int k(int a)andint k(int a, int b).Answer
(a) cannot: both signatures are
g(int); the return type and the parameter name are not part of the signature. (b) can exist together, because the order of the parameter types differs. But a call such ash(1, 1)gives the errorreference to h is ambiguous; the compiler cannot choose one of the two versions. (c) can exist together: the numbers of parameters differ.A method is written like this:
static String status(int points) { if (points >= 50) return "pass"; else if (points < 50) return "fail"; }. Does it compile? If not, what is the smallest fix?Answer
It does not compile:
missing return statement. Although the two conditions cover every integer, the compiler does not evaluate the values of conditions; because the last branch of the chain is anelse if, it assumes that control can reach the end of the method. The smallest fix is to write a plainelseinstead ofelse if (points < 50).What do the lines
System.out.println("Result: " + 2 + 3);andSystem.out.println(2 + 3 + " result");print? What doesSystem.out.printf("%.1f%n", 2.25);print on a computer set to Turkish?Answer
+works from left to right. In the first line"Result: " + 2first becomes a string, and then 3 is appended:Result: 23. In the second line2 + 3is first added as numbers:5 result. Becauseprintfuses the locale, the decimal separator is a comma and the number is rounded to one digit:2,3.You want to split the job “read a student's grades from the keyboard, compute the average, and print ‘pass’ if it is greater than 50” into methods instead of a single
main. Which methods, with which parameters and return types, could be written?Answer
One possible design:
int[] readGrades(Scanner in, int n)reads and returns the array;double average(int[] grades)computes and returns;boolean hasPassed(double avg)decides. The printing stays inmain. Each method does a single job, takes its data through parameters and returns its result.averageandhasPassedcan be tested without touching the keyboard.
3.2.16Further reading
- A. B. Downey and C. Mayfield, Think Java (2nd ed., O'Reilly, 2019), Chapter 4: explains writing methods, parameters and stack diagrams with short examples; it can be read free online.
- J. Bloch, Effective Java (3rd ed., Addison-Wesley, 2018), the “Methods” chapter: an experienced programmer's advice on checking parameters, designing method signatures, and when overloading causes trouble.
- R. C. Martin, Clean Code (Prentice Hall, 2008), Chapter 3 “Functions”: discusses the principles of short methods, doing one thing, few parameters and side-effect-free design on example code.
- J. Gosling et al., The Java Language Specification, Java SE 21, §15.12: defines with precise rules how the compiler finds the applicable methods for a call and how it chooses the most specific one.
3.2.17References
- Oracle, The Java Tutorials: “Defining Methods”, “Passing Information to a Method or a Constructor”.
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition (§8.4 Method Declarations, §6.3 Scope of a Declaration, §15.12 Method Invocation Expressions).
- P. Deitel and H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2017 (Chapter 6: Methods).
- K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022.
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., 2022.
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 4: Methods and Testing).
- J. Bloch, Effective Java, 3rd ed., Addison-Wesley, 2018.
- R. C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship, Prentice Hall, 2008.