Chapter 9: Methods
Introduction
Learning Outcomes
Write method definitions and calls.
Use parameters and return values.
Explain where local variables live.
Build short, focused, testable methods.
Basics
What Is a Function?
- In Java, functions are defined inside a class as methods.
- A method names a task and makes it a reusable unit.
- Input arrives through parameters; the result comes back as the return value.
- Example:
Math.sqrt(16)→ 4.0; we don't need to know how it works.
Basics
How a Method Runs
- Each call works with its own parameters and local variables.
Basics
Method Definition and Call
static int add(int a, int b) {
int sum = a + b;
return sum;
}
int total = add(5, 3);
System.out.println(total);- The return type is int; a and b are the formal parameters.
- 5 and 3 are the actual arguments.
- The returned value can be assigned to a variable or used in another expression.
Basics · Step through the code
Code Trace: add(5, 3)
main is running. The right-hand side comes first: add(5, 3) is called.
A new frame opens: the arguments 5 and 3 are copied into parameters a and b.
Local variable sum = 5 + 3 = 8; it lives only in add's frame.
return sum: 8 goes back to the caller and add's frame closes.
The returned value replaces the call: total = 8. a, b and sum are gone.
8 is printed.
static int add(int a, int b) { int sum = a + b; return sum; } // in main: int total = add(5, 3); System.out.println(total);
Basics · Step through the code
The Call Stack: when a method calls a method
main calls avg(9, 7). For now the stack has one frame.
The avg frame is pushed on top of main: x = 9, y = 7.
avg calls a method too: add(x, y) → the values of x and y (9, 7) are sent.
add is on top: 3 frames. Only the top one runs.
return 16: add's frame closes (last in, first out).
16 replaces the call: t = 16. avg resumes where it left off.
return t / 2 → 16 / 2 = 8 (integer division). avg's frame closes.
Back in main: o = 8. x, y, t, a and b no longer exist.
8 is printed. Frames behave like a stack: last opened, first closed.
static int add(int a, int b) { return a + b; } static int avg(int x, int y) { int t = add(x, y); return t / 2; } int o = avg(9, 7); // in main System.out.println(o);
Basics
Parts of a Method Definition
In these examples, methods live in the same class as main and are static.
Basics
The main Signature and static
public static void main(String[] args) |
|---|
public: so the JVM can call it from outside |
static: callable without creating an object |
void: returns no value |
main: the name the JVM looks for |
String[] args: command-line arguments |
void greet() { } public static void main(String[] args) { greet(); // error }
error: non-static method greet() cannot be referenced from a static context- A static method belongs to the class and is called without an object. A non-static method belongs to an object.
- A static method cannot directly use a non-static method or field; the fix is to make that method
statictoo. - When the JVM starts a program there are no objects yet, so
mainmust be static.
Return
void Methods
static void drawLine(int n) { for (int i = 0; i < n; i++) System.out.print("-"); System.out.println(); } // in main: drawLine(5); // ----- int x = drawLine(5); // ERROR: void has no value
void: the method returns no value to the call; its work is a side effect (such as printing).- So a void call cannot be part of an assignment or expression.
return;(with no value) can exit a void method early.
Return
Early Return
static void printPositive(int num) {
if (num <= 0) return;
System.out.println(num);
}- Handling special cases first can reduce nesting.
- In a value-returning method, every path must return a compatible value.
Return · Step through the code
Code Trace: printPositive(-3) and (7)
First call: argument −3.
The frame opens: num = −3.
−3 <= 0 → true → return; The method ends at once; println is never reached.
main continues on the next line: second call, argument 7.
A brand-new frame: num = 7 (the previous call's num is long gone).
7 <= 0 → false → no early return; carry on.
7 is printed.
The closing brace is reached: a void method returns here on its own.
static void printPositive(int num) { if (num <= 0) return; System.out.println(num); } // in main: printPositive(-3); printPositive(7);
Return
Compile Errors: return and Type
static int check(int n) { if (n > 0) { return 1; } }
error: missing return statement (at the closing })
static int f() { return 2.5; }
error: incompatible types: possible lossy conversion from double to int
- In a non-void method every path must end with return; here the if's false branch is missing. Fix: add
return 0;at the end. - The value must fit the return type:
return (int) 2.5;compiles (returns 2), or make the return typedouble. return 1;in avoidmethod →error: incompatible types: unexpected return value
Parameters
Parameter Passing
- Java always passes arguments by value.
- For a primitive, a copy of the value goes into the parameter: two separate boxes in memory.
- Even if the method changes its copy, the caller's variable stays the same.
- For objects (e.g. arrays), a copy of the reference is passed.
Parameters · Step through the code
Pass by Value: inc(num)
In main, num = 5: one box in main's frame.
inc(num): what is sent is the value, not the variable (5).
A separate box in the new frame: x = 5 (a copy).
x++ → x = 6. Only inc's box changed; num in main is still 5.
The method ends; its frame and x (6) are discarded. Nothing is sent back (void).
5 is printed. To change it we would write static int inc(int x) { return x + 1; } and num = inc(num);
static void inc(int x) { x++; } // in main: int num = 5; inc(num); System.out.println(num); // 5
Parameters · Step through the code
The Pass-by-Value Pitfall: swap(x, y)
In main, x = 3 and y = 5: two separate boxes in main's frame.
swap(x, y): what is sent is the values, not the variables (3 and 5).
swap's frame has two new boxes: a = 3 and b = 5 (copies). They are not linked to x and y.
t = a → t = 3: the temporary box keeps a's value.
a = b → a = 5. The old value of a now lives only in t.
b = t → b = 3. swap's copies are exchanged (a = 5, b = 3), but x and y in main were never touched.
When swap ends, its frame (a, b, t) is discarded. main still has x = 3, y = 5: only the copies were swapped. A real swap needs a returned result or an array.
static void swap(int a, int b) { int t = a; a = b; b = t; } // in main: int x = 3, y = 5; swap(x, y); System.out.println(x + " " + y); // 3 5
Parameters
Method Overloading
static int area(int side) { return side * side; } static int area(int w, int h) { return w * h; } // ERROR: only the return type differs static double area(int side) { … }
- Same name, different parameter list (number, type or order).
- Changing only the return type is not enough: the call can't tell which one is meant.
- The compiler picks the matching signature from the call's arguments.
- A familiar example:
println(int),println(double),println(String).
Parameters · Step through the code
Code Trace: which area does the compiler pick?
area(4): the compiler looks at the arguments: one int.
Two methods share the name; area(int), whose parameter count and type match, is chosen. This is decided at compile time, before the program runs.
At run time area(int) is called: side = 4 → return 16.
16 is printed.
area(3, 5): 2 int arguments → area(int, int) is chosen.
w = 3, h = 5 → return 15.
15 is printed. area(2.5) would match no signature → compile error (double → int is not automatic).
static int area(int side) { return side * side; } static int area(int w, int h) { return w * h; } System.out.println(area(4)); // main System.out.println(area(3, 5)); // main
Parameters
Variable-Length Arguments (varargs)
static int add(int... s) { int t = 0; for (int v : s) t += v; return t; } add(1, 2, 3) // 6 add() // 0 add(new int[]{4, 5}) // 9
int... s: any number of arguments; inside the method s is an int[] array.- The compiler packs the call's values into an array; with no arguments you get an empty array (s.length == 0).
- The varargs parameter must come last, and a method can have only one.
- A familiar example:
printf(String, Object...).
Parameters · Step through the code
Variable-Length Arguments: add(1, 2, 3)
add(1, 2, 3): the compiler packs the three values into the array new int[]{1, 2, 3}.
s is an int[] array: s = {1, 2, 3}, s.length = 3.
t = 0: a local box for the total.
Enhanced for, pass 1: v = 1 → t = 0 + 1 = 1.
Pass 2: v = 2 → t = 1 + 2 = 3.
Pass 3: v = 3 → t = 3 + 3 = 6. No elements left.
return t → returns 6. v went out of scope with the loop.
6 is printed. add's frame (s, t) is gone.
static int add(int... s) { int t = 0; for (int v : s) t += v; return t; } // in main: System.out.println(add(1, 2, 3)); System.out.println(add());
Parameters · Step through the code
Empty Call: add()
add(): no arguments → the compiler passes an empty array (new int[0]), not null.
s is an empty array: s.length = 0.
t = 0.
The array is empty: the body never runs, t stays 0.
return t → returns 0.
0 is printed. An empty call is not an error; the result is 0, the identity for addition.
static int add(int... s) { int t = 0; for (int v : s) t += v; return t; } // in main: System.out.println(add(1, 2, 3)); System.out.println(add());
Scope
Local Scope
- Parameters and variables declared inside a method are local.
- A variable declared in a block (
{ }) is visible only in that block and blocks nested in it. - Two local variables with the same name cannot be declared in the same scope.
- Another method's local variables are not accessible.
Scope · Step through the code
Scope Example: calc(3)
main calls calc(3).
The method scope opens: parameter n = 3.
sum is in method scope: visible until the end of the method.
3 > 0 → true: enter the if block; a new inner scope opens.
part = 3 × 2 = 6: exists only inside the if block.
The inner block can reach sum in the outer scope: sum = 0 + 6 = 6.
The block closed: part is gone. Writing part here would be a compile error.
return 6: the method scope closes too (n and sum are discarded).
The returned 6 becomes println's argument and is printed.
static int calc(int n) { int sum = 0; if (n > 0) { int part = n * 2; sum += part; } return sum; } System.out.println(calc(3)); // main
Scope
Scope: Variables with the Same Name
int x = 1; if (x > 0) { int x = 5; // error }
error: variable x is already defined in method main(String[])- An inner block cannot reuse the name of a local variable from the outer scope; a local does not shadow another local.
- Parameters are local too:
int a = 3;insideadd(int a, int b)gives the same error. - A variable is gone when its block ends: after
for (int i …) { }you may writeint i = 7;. - A local variable with the same name as a static field compiles; the local one is visible and the field is unchanged.
Library
Common Library Methods: Math
| Call | Result | Return type | Note |
|---|---|---|---|
Math.abs(-7) | 7 | int | absolute value (overloaded: int, long, double…) |
Math.max(3, 9) | 9 | int | returns the larger one |
Math.sqrt(16) | 4.0 | double | square root; always a double |
Math.pow(2, 10) | 1024.0 | double | power; needs (int) to assign to an int |
Math.round(2.5) | 3 | long | rounds to the nearest integer |
- Check the documentation for parameters, return type and special cases (e.g.
Math.sqrt(-1)→ NaN).
Design
Abstraction
- A method hides implementation details from the calling code.
- A well-named method says what it does; how stays in the body.
- As long as the signature stays the same, callers are unaffected by changes to the body.
Design
Decomposition
- A large task is split into subtasks, each with one responsibility.
- For each subtask, define its input, output and error behavior.
- A top-level method combines them in a sensible order; it reads like a table of contents.
Design
Good Method Design
| Principle | Question |
|---|---|
| Single task | Can the method be described in one sentence? |
| Meaningful name | Does the name state the result or the action? |
| Few parameters | Are all the inputs necessary? |
| Clear result | Are the return value and side effects clear? |
| Testability | Can the method be tested on its own? |
Example
Contract First
- The method name should state clearly what it does.
- Define the valid range of each parameter.
- Know what the return value means and how errors behave.
// Task : returns the number of decimal digits. // Input : any int (may be negative). // Output: 1..10; 1 for 0, 3 for -507. static int digitCount(int num) { … }
Example
Even / Odd
static boolean isEven(int num) {
return num % 2 == 0;
}- A boolean result can be used directly in decisions.
- The method returns the result instead of printing it.
Examples · Step through the code
Code Trace: isEven(7)
To evaluate the if condition, isEven(7) is called first.
Frame opens: num = 7.
7 % 2 = 1 → 1 == 0 → false. return false.
The return value replaces the call: if (false) → the then branch is skipped.
The else branch prints odd. The method only computed; the caller decides what to print.
static boolean isEven(int num) { return num % 2 == 0; } // in main: if (isEven(7)) System.out.println("even"); else System.out.println("odd");
Example
Counting Digits
static int digitCount(int num) { long rest = Math.abs((long) num); if (rest == 0) return 1; int count = 0; while (rest > 0) { count++; rest /= 10; } return count; } System.out.println(digitCount(-507));
(long)converts first:Math.abs(-2147483648)would stay negative as an int.- Early return for 0: 1 digit.
- The result is returned, not printed; the caller can use it freely.
Examples · Step through the code
Code Trace: digitCount(-507)
For println's argument, digitCount(-507) is called first.
Frame opens: num = −507.
Math.abs((long) −507) → rest = 507. (A library method is a call too: it returns a value.)
507 == 0 → false: no early return.
Counter count = 0.
Pass 1: 507 > 0 → count = 1, rest = 507 / 10 = 50.
Pass 2: 50 > 0 → count = 2, rest = 50 / 10 = 5.
Pass 3: 5 > 0 → count = 3, rest = 5 / 10 = 0.
0 > 0 → false: the loop ends.
return 3: the frame closes.
3 replaces the call: println(3) → 3 is printed.
static int digitCount(int num) { long rest = Math.abs((long) num); if (rest == 0) return 1; int count = 0; while (rest > 0) { count++; rest /= 10; } return count; } System.out.println(digitCount(-507));
Example
Is It Prime?
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= n / i; i++)
if (n % i == 0) return false;
return true;
}- Return early as soon as the first divisor is found.
Examples · Step through the code
Code Trace: isPrime(15) and isPrime(7)
isPrime(15) is called.
n = 15: 15 < 2 → false.
2 <= 15/2 = 7 → true; 15 % 2 = 1 → not a divisor, i++.
3 <= 5 → true; 15 % 3 = 0 → return false: the remaining passes never run (early return).
The returned false goes to println and is printed.
isPrime(7) is called.
n = 7: 7 < 2 → false.
2 <= 7/2 = 3 → true; 7 % 2 = 1 → not a divisor, i++.
3 <= 7/3 = 2 → false: no divisor up to √7.
The loop finished without an early return → return true.
The returned true goes to println and is printed.
static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= n / i; i++) if (n % i == 0) return false; return true; } System.out.println(isPrime(15)); // main System.out.println(isPrime(7)); // main
Examples · Step through the code
gcd: Euclid's algorithm (48, 18)
Euclid's algorithm finds the greatest common divisor (GCD): gcd(a, b) = gcd(b, a % b); when b = 0 the answer is a.
The frame opens: a = 48, b = 18.
Condition: 18 != 0 → true.
r = 48 % 18 = 12; a = 18, b = 12. (gcd(48, 18) = gcd(18, 12))
Condition: 12 != 0 → true.
r = 18 % 12 = 6; a = 12, b = 6. (gcd(18, 12) = gcd(12, 6))
Condition: 6 != 0 → true.
r = 12 % 6 = 0; a = 6, b = 0. (gcd(12, 6) = gcd(6, 0))
Condition: 0 != 0 → false.
return Math.abs(6) → 6. Math.abs keeps the result positive even for negative input.
6 is printed: 48 = 6 × 8, 18 = 6 × 3. Only 3 passes, much faster than trying every number from 1 to 18.
static int gcd(int a, int b) { while (b != 0) { int r = a % b; a = b; b = r; } return Math.abs(a); } System.out.println(gcd(48, 18)); // main
Examples · Step through the code
lcm(12, 18): a method calling a method
main calls lcm(12, 18).
lcm frame: a = 12, b = 18.
a and b are nonzero, so line 2 is passed. To evaluate the expression, lcm calls gcd(a, b): 3 frames on the stack.
gcd runs its own loop: (12, 18) → (18, 12) → (12, 6) → (6, 0) → return 6. The names match, but gcd's a and b are separate boxes.
6 replaces the call: 12 / 6 * 18 = 2 * 18 = 36. Dividing first keeps a * b from overflowing.
return 36: lcm's frame closes.
36 is printed. Calling another method keeps the code short: no duplication.
static int lcm(int a, int b) { if (a == 0 || b == 0) return 0; return Math.abs(a / gcd(a, b) * b); } // gcd: Euclid's algorithm System.out.println(lcm(12, 18)); // main
Examples · Step through the code
Reuse: max3(4, 9, 7)
main wants the largest of three numbers.
max3 frame: a = 4, b = 9, c = 7.
In a nested call the inner one is evaluated first: max(4, 9).
New frame (a = 4, b = 9): 4 > 9 → false.
return b → 9.
The expression simplifies to max(9, 7). The same method is called a second time.
New frame (a = 9, b = 7): 9 > 7 → true → return a → 9.
max3 returns 9 as well.
9 is printed. The comparison logic lives in one place (max), so a bug is fixed once.
static int max(int a, int b) { if (a > b) return a; return b; } static int max3(int a, int b, int c) { return max(max(a, b), c); } System.out.println(max3(4, 9, 7)); // main
Examples · Step through the code
Methods returning double: temperature conversion
fahrenheit(25): the int argument 25 is widened to 25.0 for the double parameter.
c = 25.0.
25.0 × 9 = 225.0; / 5 = 45.0; + 32 = 77.0 → return.
f = 77.0 (double).
77.0 is printed (with .0, since it is a double).
celsius(f): the value of f (77.0) is copied.
(77.0 − 32) × 5 / 9 = 45.0 × 5 / 9 = 25.0. With 5 / 9 * (f - 32), integer division would make 5 / 9 equal 0!
25.0 is printed: the two methods are inverses (a nice check for testing).
static double fahrenheit(double c) { return c * 9 / 5 + 32; } static double celsius(double f) { return (f - 32) * 5 / 9; } double f = fahrenheit(25); // main System.out.println(f); System.out.println(celsius(f));
Example
Pure Methods and Side Effects
- A method that returns the same result for the same input and changes no outside state is easier to test.
- Computing and printing can live in separate methods.
- When a side effect is needed, name it clearly and keep it contained.
square(4) is always 16; usable anywhere.
Only prints; the result can't be used in another computation.
Summary
Chapter Summary
- A method names a task, takes input through parameters and can return a result.
- Java always passes arguments by value.
- Overloading reuses one name with different parameter lists.
- Scope determines where a variable can be accessed.
- A method can call another (lcm → gcd, max3 → max); each call opens its own frame on the stack.
- A method that returns its result instead of printing it is easier to test and reuse.
Summary
Review Questions
- What is the difference between a parameter and an argument?
- When is a void method appropriate?
- Why doesn't
numchange after callinginc(num)? - Which part must differ in overloading? Why can't
int f(int)anddouble f(int)coexist? - Why does
isEvenreturn a boolean instead of printing?
Summary
Exercises
- Write
static boolean isLeap(int year)(the 4/100/400 rule) and test it with 1900, 2000, 2024. - Write
static long factorial(int n)and use it instatic long choose(int n, int r)= n! / (r! (n − r)!). - Write
static int reverse(int num)and astatic boolean isPalindrome(int num)that calls it. static double avg(int a, int b, int c): why can(a + b + c) / 3give a wrong result? Fix it.- Overloading: add
max(double, double); which one doesmax(3, 4.5)call? - Write a
mainthat usesisPrimeto list the twin primes in 1..100 (5–7, 11–13 …).
Summary
References
- Deitel and Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, The Java Tutorials: Defining Methods, Passing Information to a Method.
- Oracle, Java Language Specification SE 21: Chapter 8, Classes (§8.4 Method Declarations).
- Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 2.1 Static Methods.
- Downey and Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online edition).