Chapter 9: Methods

Computer Fundamentals and Introduction to Programming
DefinitionParametersReturnScopeExamples
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Defining

Write method definitions and calls.

Data flow

Use parameters and return values.

Scope

Explain where local variables live.

Design

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.
input53add(a, b)output8parametersbody (details hidden)return value

Basics

How a Method Runs

mainint x = 5;int t = add(x, 3);System.out.println(t);addstatic int add(int a, int b) { return a + b;}① call: a = 5, b = 3② return 8 → 8 replaces the call③ main resumes where it left off: t = 8, then println
Evaluate the arguments
Copy into parameters
Run the body
Return a value
Resume the caller
  • 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);
int total = add(5, 3);add(5,3)actual argumentsvalue is copied53abformal parameterssum = 5 + 3 = 8returntotal = 8
  • 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()total = add(5, 3)

main is running. The right-hand side comes first: add(5, 3) is called.

main()total = add(5, 3)adda5b3

A new frame opens: the arguments 5 and 3 are copied into parameters a and b.

main()total = add(5, 3)adda5b3sum8

Local variable sum = 5 + 3 = 8; it lives only in add's frame.

main()total = add(5, 3)adda5b3sum8closedreturn 8

return sum: 8 goes back to the caller and add's frame closes.

main()total8total = 8

The returned value replaces the call: total = 8. a, b and sum are gone.

main()total8

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()o = avg(9, 7)

main calls avg(9, 7). For now the stack has one frame.

main()o = avg(9, 7)avgx9y7

The avg frame is pushed on top of main: x = 9, y = 7.

main()o = avg(9, 7)avgx9y7t = add(x, y)

avg calls a method too: add(x, y) → the values of x and y (9, 7) are sent.

main()o = avg(9, 7)avgx9y7t = add(x, y)adda9b7

add is on top: 3 frames. Only the top one runs.

main()o = avg(9, 7)avgx9y7t = add(x, y)adda9b7closedreturn 16

return 16: add's frame closes (last in, first out).

main()o = avg(9, 7)avgx9y7t16t = 16

16 replaces the call: t = 16. avg resumes where it left off.

main()o = avg(9, 7)avgx9y7t16closedreturn 8

return t / 2 → 16 / 2 = 8 (integer division). avg's frame closes.

main()o8o = 8

Back in main: o = 8. x, y, t, a and b no longer exist.

main()o8

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

public static int add(int a, int b) {accesswho can call it?modifierno object neededreturn typewhat comes back?namename of the taskparameter listwhich inputs?int sum = a + b;return sum;}body: statements run on each callreturn gives a value of the return typesignature = name + paramstypes: add(int, int)

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 static too.
  • When the JVM starts a program there are no objects yet, so main must 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.
add(5, 3)return8int t = 8;the value replaces the calldrawLine(5)-----prints (side effect), returns nothingint x = drawLine(5); ✗

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.
printPositive(num)num <= 0 ?yesreturn;early exitnoprintln(num);method endsprintPositive(-3) → no outputprintPositive(7) → 7

Return · Step through the code

Code Trace: printPositive(-3) and (7)

main()printPositive(-3)

First call: argument −3.

main()printPositive(-3)printPositivenum-3

The frame opens: num = −3.

main()printPositive(-3)printPositivenum-3closedreturn (no value)

−3 <= 0 → true → return; The method ends at once; println is never reached.

main()printPositive(7)

main continues on the next line: second call, argument 7.

main()printPositive(7)printPositivenum7

A brand-new frame: num = 7 (the previous call's num is long gone).

main()printPositive(7)printPositivenum7

7 <= 0 → false → no early return; carry on.

main()printPositive(7)printPositivenum7

7 is printed.

main()printPositive(7)printPositivenum7closed

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 type double.
  • return 1; in a void method → 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.
main()num5inc(num)x5value is copied

Parameters · Step through the code

Pass by Value: inc(num)

main()num5

In main, num = 5: one box in main's frame.

main()num5inc(num)

inc(num): what is sent is the value, not the variable (5).

main()num5incx5copy

A separate box in the new frame: x = 5 (a copy).

main()num5incx6

x++ → x = 6. Only inc's box changed; num in main is still 5.

main()num5incx6closed

The method ends; its frame and x (6) are discarded. Nothing is sent back (void).

main()num5

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)

main()x3y5

In main, x = 3 and y = 5: two separate boxes in main's frame.

main()x3y5swap(x, y)

swap(x, y): what is sent is the values, not the variables (3 and 5).

main()x3y5swap(x, y)swapa3b5copy

swap's frame has two new boxes: a = 3 and b = 5 (copies). They are not linked to x and y.

main()x3y5swap(x, y)swapa3b5t3

t = a → t = 3: the temporary box keeps a's value.

main()x3y5swap(x, y)swapa5b5t3

a = b → a = 5. The old value of a now lives only in t.

main()x3y5swap(x, y)swapa5b3t3

b = t → b = 3. swap's copies are exchanged (a = 5, b = 3), but x and y in main were never touched.

main()x3y5

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).
area(4)1 int argumentarea(int side)16area(3, 5)2 int argumentsarea(int w, int h)15The compiler checks argument count and types, not the return type.

Parameters · Step through the code

Code Trace: which area does the compiler pick?

area(4)call (arguments)area(int)area(int, int)signatures the compiler sees

area(4): the compiler looks at the arguments: one int.

area(4)call (arguments)area(int)✓ matchesarea(int, int)✗ needs 2 parameterssignatures the compiler sees

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.

area(4)call (arguments)area(int)✓ matchesarea(int, int)✗ needs 2 parameterssignatures the compiler sees

At run time area(int) is called: side = 4 → return 16.

area(4)call (arguments)area(int)✓ matchesarea(int, int)✗ needs 2 parameterssignatures the compiler sees

16 is printed.

area(3, 5)call (arguments)area(int)✗ needs 1 parameterarea(int, int)✓ matchessignatures the compiler sees

area(3, 5): 2 int arguments → area(int, int) is chosen.

area(3, 5)call (arguments)area(int)✗ needs 1 parameterarea(int, int)✓ matchessignatures the compiler sees

w = 3, h = 5 → return 15.

area(3, 5)call (arguments)area(int)✗ needs 1 parameterarea(int, int)✓ matchessignatures the compiler sees

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)

main()add(1, 2, 3)

add(1, 2, 3): the compiler packs the three values into the array new int[]{1, 2, 3}.

main()add(1, 2, 3)adds123

s is an int[] array: s = {1, 2, 3}, s.length = 3.

main()add(1, 2, 3)adds123t0

t = 0: a local box for the total.

main()add(1, 2, 3)adds123t1v1

Enhanced for, pass 1: v = 1 → t = 0 + 1 = 1.

main()add(1, 2, 3)adds123t3v2

Pass 2: v = 2 → t = 1 + 2 = 3.

main()add(1, 2, 3)adds123t6v3

Pass 3: v = 3 → t = 3 + 3 = 6. No elements left.

main()add(1, 2, 3)adds123t6

return t → returns 6. v went out of scope with the loop.

main()

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

main()add()

add(): no arguments → the compiler passes an empty array (new int[0]), not null.

main()add()adds[ ] empty

s is an empty array: s.length = 0.

main()add()adds[ ] emptyt0

t = 0.

main()add()adds[ ] emptyt0

The array is empty: the body never runs, t stays 0.

main()add()adds[ ] emptyt0

return t → returns 0.

main()

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.
calc(int n) { … } — method scopen3sum0if (n > 0) { … } — block scopepart6

Scope · Step through the code

Scope Example: calc(3)

calc(int n) { … } — method scope

main calls calc(3).

calc(int n) { … } — method scopen3

The method scope opens: parameter n = 3.

calc(int n) { … } — method scopen3sum0

sum is in method scope: visible until the end of the method.

calc(int n) { … } — method scopen3sum0if (n > 0) { … } — block scope

3 > 0 → true: enter the if block; a new inner scope opens.

calc(int n) { … } — method scopen3sum0if (n > 0) { … } — block scopepart6

part = 3 × 2 = 6: exists only inside the if block.

calc(int n) { … } — method scopen3sum6if (n > 0) { … } — block scopepart6

The inner block can reach sum in the outer scope: sum = 0 + 6 = 6.

calc(int n) { … } — method scopen3sum6if (n > 0) { … } — block scopepart → block ended, variable gone

The block closed: part is gone. Writing part here would be a compile error.

calc(int n) { … } — method scopen3sum6if (n > 0) { … } — block scopepart → block ended, variable gone

return 6: the method scope closes too (n and sum are discarded).

calc(int n) { … } — method scope

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
}
scope of the main methodx1outer x: visible inside toothe if (x > 0) { … } blockint x = 5;✗ x is already defined
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; inside add(int a, int b) gives the same error.
  • A variable is gone when its block ends: after for (int i …) { } you may write int 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

CallResultReturn typeNote
Math.abs(-7)7intabsolute value (overloaded: int, long, double…)
Math.max(3, 9)9intreturns the larger one
Math.sqrt(16)4.0doublesquare root; always a double
Math.pow(2, 10)1024.0doublepower; needs (int) to assign to an int
Math.round(2.5)3longrounds to the nearest integer
  • Check the documentation for parameters, return type and special cases (e.g. Math.sqrt(-1) → NaN).

Design

Abstraction

calling codeMath.sqrt(16)visible: signature + contractdouble sqrt(double x)√x for x ≥ 0hidden: body? ? ?may change
  • 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

gradeReport()readGrades()inputcomputeAvg()pure calcletterGrade(avg)decisionwriteReport(…)output
  • 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

PrincipleQuestion
Single taskCan the method be described in one sentence?
Meaningful nameDoes the name state the result or the action?
Few parametersAre all the inputs necessary?
Clear resultAre the return value and side effects clear?
TestabilityCan 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) { … }
input (precondition)any intmay be negativedigitCountoutput (postcondition)1 … 10returns, does not printexample:0 → 1-507 → 32147483647 → 10-2147483648 → 10

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.
numnum % 2isEven(num)71false100true-40true-3-1falseIn Java the remainder of a negative number can be negative (-3 % 2 = -1), so we test == 0.

Examples · Step through the code

Code Trace: isEven(7)

main()if (isEven(7))

To evaluate the if condition, isEven(7) is called first.

main()if (isEven(7))isEvennum7

Frame opens: num = 7.

main()if (isEven(7))isEvennum7closedreturn false

7 % 2 = 1 → 1 == 0 → false. return false.

main()if (false)

The return value replaces the call: if (false) → the then branch is skipped.

main()

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)

main()println(digitCount(-507))

For println's argument, digitCount(-507) is called first.

main()println(digitCount(-507))digitCountnum-507

Frame opens: num = −507.

main()println(digitCount(-507))digitCountnum-507rest507

Math.abs((long) −507) → rest = 507. (A library method is a call too: it returns a value.)

main()println(digitCount(-507))digitCountnum-507rest507

507 == 0 → false: no early return.

main()println(digitCount(-507))digitCountnum-507rest507count0

Counter count = 0.

main()println(digitCount(-507))digitCountnum-507rest50count1

Pass 1: 507 > 0 → count = 1, rest = 507 / 10 = 50.

main()println(digitCount(-507))digitCountnum-507rest5count2

Pass 2: 50 > 0 → count = 2, rest = 50 / 10 = 5.

main()println(digitCount(-507))digitCountnum-507rest0count3

Pass 3: 5 > 0 → count = 3, rest = 5 / 10 = 0.

main()println(digitCount(-507))digitCountnum-507rest0count3

0 > 0 → false: the loop ends.

main()println(digitCount(-507))digitCountnum-507rest0count3closedreturn 3

return 3: the frame closes.

main()println(3)

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.
isPrime(37): only i with i ≤ n / i are tried (√37 ≈ 6.08)in / i37 % i2181312149157266175not triedNo remainder is 0; for i = 7, 7 > 37 / 7 = 5 → the loop ends → return true

Examples · Step through the code

Code Trace: isPrime(15) and isPrime(7)

main()println(isPrime(15))

isPrime(15) is called.

main()println(isPrime(15))isPrimen15

n = 15: 15 < 2 → false.

main()println(isPrime(15))isPrimen15i2

2 <= 15/2 = 7 → true; 15 % 2 = 1 → not a divisor, i++.

main()println(isPrime(15))isPrimen15i3closedreturn false

3 <= 5 → true; 15 % 3 = 0 → return false: the remaining passes never run (early return).

main()println(false)

The returned false goes to println and is printed.

main()println(isPrime(7))

isPrime(7) is called.

main()println(isPrime(7))isPrimen7

n = 7: 7 < 2 → false.

main()println(isPrime(7))isPrimen7i2

2 <= 7/2 = 3 → true; 7 % 2 = 1 → not a divisor, i++.

main()println(isPrime(7))isPrimen7i3

3 <= 7/3 = 2 → false: no divisor up to √7.

main()println(isPrime(7))isPrimen7closedreturn true

The loop finished without an early return → return true.

main()println(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)

main()println(gcd(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.

main()println(gcd(48, 18))gcda48b18

The frame opens: a = 48, b = 18.

main()println(gcd(48, 18))gcda48b18

Condition: 18 != 0 → true.

main()println(gcd(48, 18))gcda18b12r12

r = 48 % 18 = 12; a = 18, b = 12. (gcd(48, 18) = gcd(18, 12))

main()println(gcd(48, 18))gcda18b12

Condition: 12 != 0 → true.

main()println(gcd(48, 18))gcda12b6r6

r = 18 % 12 = 6; a = 12, b = 6. (gcd(18, 12) = gcd(12, 6))

main()println(gcd(48, 18))gcda12b6

Condition: 6 != 0 → true.

main()println(gcd(48, 18))gcda6b0r0

r = 12 % 6 = 0; a = 6, b = 0. (gcd(12, 6) = gcd(6, 0))

main()println(gcd(48, 18))gcda6b0

Condition: 0 != 0 → false.

main()println(gcd(48, 18))gcda6b0closedreturn 6

return Math.abs(6) → 6. Math.abs keeps the result positive even for negative input.

main()println(6)

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()println(lcm(12, 18))

main calls lcm(12, 18).

main()println(lcm(12, 18))lcma12b18

lcm frame: a = 12, b = 18.

main()println(lcm(12, 18))lcma12b18a / gcd(a, b) * bgcda12b18

a and b are nonzero, so line 2 is passed. To evaluate the expression, lcm calls gcd(a, b): 3 frames on the stack.

main()println(lcm(12, 18))lcma12b18a / gcd(a, b) * bgcda6b0closedreturn 6

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.

main()println(lcm(12, 18))lcma12b1812 / 6 * 18 = 36

6 replaces the call: 12 / 6 * 18 = 2 * 18 = 36. Dividing first keeps a * b from overflowing.

main()println(lcm(12, 18))lcma12b18closedreturn 36

return 36: lcm's frame closes.

main()println(36)

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()println(max3(4, 9, 7))

main wants the largest of three numbers.

main()println(max3(4, 9, 7))max3a4b9c7

max3 frame: a = 4, b = 9, c = 7.

main()println(max3(4, 9, 7))max3a4b9c7max(max(4, 9), 7)

In a nested call the inner one is evaluated first: max(4, 9).

main()println(max3(4, 9, 7))max3a4b9c7max(max(4, 9), 7)maxa4b9

New frame (a = 4, b = 9): 4 > 9 → false.

main()println(max3(4, 9, 7))max3a4b9c7max(max(4, 9), 7)maxa4b9closedreturn 9

return b → 9.

main()println(max3(4, 9, 7))max3a4b9c7max(9, 7)

The expression simplifies to max(9, 7). The same method is called a second time.

main()println(max3(4, 9, 7))max3a4b9c7max(9, 7)maxa9b7closedreturn 9

New frame (a = 9, b = 7): 9 > 7 → true → return a → 9.

main()println(max3(4, 9, 7))max3a4b9c7closedreturn 9

max3 returns 9 as well.

main()println(9)

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

main()f = fahrenheit(25)

fahrenheit(25): the int argument 25 is widened to 25.0 for the double parameter.

main()f = fahrenheit(25)fahrenheitc25.0

c = 25.0.

main()f = fahrenheit(25)fahrenheitc25.0closedreturn 77.0

25.0 × 9 = 225.0; / 5 = 45.0; + 32 = 77.0 → return.

main()f77.0f = 77.0

f = 77.0 (double).

main()f77.0

77.0 is printed (with .0, since it is a double).

main()f77.0println(celsius(f))celsiusf77.0

celsius(f): the value of f (77.0) is copied.

main()f77.0println(celsius(f))celsiusf77.0closedreturn 25.0

(77.0 − 32) × 5 / 9 = 45.0 × 5 / 9 = 25.0. With 5 / 9 * (f - 32), integer division would make 5 / 9 equal 0!

main()f77.0println(25.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.
Purestatic int square(int x) { return x * x; }

square(4) is always 16; usable anywhere.

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

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

  1. What is the difference between a parameter and an argument?
  2. When is a void method appropriate?
  3. Why doesn't num change after calling inc(num)?
  4. Which part must differ in overloading? Why can't int f(int) and double f(int) coexist?
  5. Why does isEven return a boolean instead of printing?

Summary

Exercises

  1. Write static boolean isLeap(int year) (the 4/100/400 rule) and test it with 1900, 2000, 2024.
  2. Write static long factorial(int n) and use it in static long choose(int n, int r) = n! / (r! (n − r)!).
  3. Write static int reverse(int num) and a static boolean isPalindrome(int num) that calls it.
  4. static double avg(int a, int b, int c): why can (a + b + c) / 3 give a wrong result? Fix it.
  5. Overloading: add max(double, double); which one does max(3, 4.5) call?
  6. Write a main that uses isPrime to 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).

The End

Chapter 9: Methods
Previous: Chapter 8: Loops · Next: Chapter 10: Arrays
1 / 1Sercan KÜLCÜ. All rights reserved.