Chapter 3.2: Methods

Object Oriented Programming with Java
Definition and callsParameters and return valuesThe call stackOverloading Built-in Java methodsScopeAbstraction and design
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Defining and calling

Write a method with an access modifier, return type, name and parameter list; call it with arguments and use its return value.

Tracing execution

Show step by step how frames are pushed and popped on the call stack, and how arguments are copied by value.

Overloading

Tell same-named methods apart by their parameter lists; predict which version the compiler picks from the argument types.

Built-in methods

System.out and Math: use their methods correctly; know the commonly used classes and packages of the Java library.

Scope

Explain the scope and lifetime of local variables, class fields and nested blocks.

Design

Design good methods using abstraction, generalization, DRY and single responsibility; break a problem into methods.

Methods

What Is a Method?

A function is a piece of code that does one job, has a name, and can be used again and again. In Java, functions always live inside a class and are called methods.

  • A method is defined by the parameters it takes and its return type.
  • Methods make code more readable and reduce repetition.
  • They encourage modular, well-organized code.
  • They split a program into small, manageable pieces.
Analogy: a recipe

"Brew tea" is a recipe: written once, followed as often as you like. The ingredients are the parameters, and the tea you get is the return value. Whoever follows the recipe doesn't have to rethink every step.

The main we have been writing is also a method; System.out.println(...) is a call to a built-in method.

Methods

Input – Process – Output

Every method can be seen in three stages:

Input num1 = 5num2 = 3 Process add(...) result = num1 + num2 Output return 8 what to work on? performs a specific task the result is returned
Input

The method receives data: parameters. They determine what the method works on.

Process

The method processes the input with the statements in its body and performs a specific task.

Output

The process produces a result, which return hands back to the caller.

Like f(x) = x² in math: x is the input, squaring is the process, x² is the output. Some methods have no input or no output (void).

Definition and Calls

Defining a Method

public int add (int num1, int num2) { accessmodifier returntype method name parameter list (type + name) signature = name + parameter types int result = num1 + num2; return result; } body(code block) ← return the result
publicAccess modifier: says who may call the method.
intReturn type: the type of the value the method gives back; if it returns nothing, void.
addMethod name: a verb or verb phrase starting with a lowercase letter (camelCase).
(int num1, int num2)Parameters: the method's inputs; each has a type and a name.
{ ... }Code block (body): the statements that run when the method is called.

The add method takes two input parameters, num1 and num2, adds them and returns the result.

Definition and Calls

Calling a Method

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);
    }
}
Output
Sum: 8
  • add(5, 3) is a call: control goes to the method and, when it finishes, comes back to where the call was made.
  • In the call, 5 and 3 are arguments; in the definition, num1, num2 are parameters.
  • The call returns 8; this value is assigned to the result variable.
  • The number, order and types of the arguments must match the parameters.
  • static: the method can be called directly from main, without creating an object.

Definition and Calls · Step-by-step code trace

Call and Return: Step by Step

Stackmain()

A program always starts in its main method. The stack holds only the main frame.

Stackadd(5, 3)num15num23main()result?

add(5, 3) is called: a new frame is pushed, and the arguments are copied.

Stackadd(5, 3)num15num23result8main()result?

The body runs: result = 5 + 3 = 8. This result is add's local variable.

Stackadd(5, 3)num15num23result8main()result?

return result; sends 8 back to the caller and ends the method; the frame is popped.

Stackmain()result8

Control returns to the calling line: the returned 8 is assigned to main's result variable. The two result variables are different.

Stackmain()result8

println is also a method call: it prints Sum: 8.

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);
}

Definition and Calls

Sample Methods

public class SampleMethods {
    // adds two numbers
    public static int add(int num1, int num2) {
        return num1 + num2;
    }
    // computes a square
    public static double square(double num) {
        return num * num;
    }
    // prints hello world
    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();
    }
}
Output
9
2.25
Hello, World!
MethodInputOutput
add2 × intint
square1 × doubledouble
helloWorldnonenone (void)

A value-returning method's result is used in an expression; a void method is called on its own as a statement.

Definition and Calls

return and void

  • return expression; hands the value to the caller and ends the method at once; the lines after it don't run.
  • The returned value's type must be compatible with the declared return type (widening int → double is allowed).
  • In a value-returning method, every path must end with a return; otherwise the compiler reports missing return statement.
  • void methods return no value; a bare return; can be used to exit early.
public class EarlyReturn {
    static void printQuotient(int dividend, int divisor) {
        if (divisor == 0) {
            System.out.println("Cannot divide by zero!");
            return;                      // leave the method now
        }
        System.out.println(dividend / divisor);
    }
    public static void main(String[] args) {
        printQuotient(10, 2);
        printQuotient(7, 0);
    }
}
Output
5
Cannot divide by zero!

Definition and Calls

static Calls and Calls on an Object

static method
static int add(int num1, int num2) {
    return num1 + num2;
}
// directly, inside main:
int result = add(5, 3);

static methods belong to the class; no object is needed. From another class they are called as ClassName.method(), like Math.sqrt(16).

object (instance) method
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
    }
}

Methods that are not static are called on an object: first create the object with new, then call calc.add(5, 3).

If the definition lacks static, then inside main, writing just add(5, 3) is a compile error:
non-static method add(int,int) cannot be referenced from a static context

Definition and Calls · Step-by-step code trace

Pass by Value

Can a method change the variable it is given?

Stackmain()num5

main: num = 5.

Stackincrease(5)num5main()num5

The call sends a copy of the value (5). increase's num is a separate box; sharing the same name means nothing.

Stackincrease(5)num15main()num5

Only the copy changes: increase's num becomes 15, main's is still 5.

Stackincrease(5)num15main()num5

increase prints 15.

Stackmain()num5

increase is done; its frame and copy are gone. main's num 5 remains: Java passes arguments by value.

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);
}

Definition and Calls · Step-by-step code trace

A Copy of the Reference: Tracing the Code

call stackheapmaina12

a is a reference: the array object lives on the heap, and a holds its address.

call stackheapmainax112

x = 1: the primitive value is stored right in the frame.

call stackheapmainax112modifydx1

The call: d gets a's reference copy, x gets a copy of 1. d and a refer to the same array.

call stackheapmainax1502modifydx1

d[0] = 50: the shared array changes; main will see the change too.

call stackheapmainax1502modifydx50

x = 50: only modify's copy changes.

call stackheapmainax1502modifydx5000

d = new int[2]: d now refers to a new array. a is unaffected; the link is broken.

call stackheapmainax1502modifydx50050

d[1] = 50 is written to the new array; main's array is unchanged.

call stackheapmainax1502

The method is done; its frame is gone. Nothing refers to the new array any more (the garbage collector will reclaim it).

call stackheapmainax1502

50 2 1: the array's contents changed, x did not. Java passes everything by value; a reference is just a value that gets copied.

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);
}

Definition and Calls

Method Overloading

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));
    }
}
Output
5
3.7
6

Overloading: several methods with the same name can live in one class as long as their parameter lists differ.

  • They can differ in the number, type or order of parameters.
  • The compiler looks at a call's arguments and decides which method runs at compile time.
  • Two methods that differ only in return type are not overloads: method sum(int,int) is already defined is what you get.
  • println is overloaded too: println(int), println(String), println(double)…

Definition and Calls · Step-by-step code trace

Which sum Runs? Step by Step

sum(4, 6)arguments: int, intsum(int, int)✓ exact matchsum(double, double)✓ fits by wideningsum(int, int, int)✗ wrong count

There are three methods named sum. The first call's arguments are (int, int): the three-parameter version is ruled out; (int, int) matches exactly, so it is chosen.

sum(4, 6)arguments: int, intsum(int, int)✓ exact matcha = 4, b = 6sum(double, double)✓ fits by wideningsum(int, int, int)✗ wrong count

sum(int, int) runs: a = 4, b = 6.

sum(4, 6)arguments: int, intsum(int, int)✓ exact matchreturns 10sum(double, double)✓ fits by wideningsum(int, int, int)✗ wrong count

10 is returned and printed.

sum(4, 2.5)arguments: int, doublesum(int, int)✗ 2.5 is not an intsum(double, double)✓ 4 → 4.0sum(int, int, int)✗ wrong count

(int, double): 2.5 to int? Not implicitly, so (int, int) is out. 4 is widened to 4.0 → sum(double, double).

sum(4, 2.5)arguments: int, doublesum(int, int)✗ 2.5 is not an intsum(double, double)✓ 4 → 4.0a = 4.0, b = 2.5sum(int, int, int)✗ wrong count

a = 4.0, b = 2.5: the parameters are double.

sum(4, 2.5)arguments: int, doublesum(int, int)✗ 2.5 is not an intsum(double, double)✓ 4 → 4.0returns 6.5sum(int, int, int)✗ wrong count

6.5 is returned and printed.

sum(7, 1, 2)arguments: int, int, intsum(int, int)✗ wrong countsum(double, double)✗ wrong countsum(int, int, int)✓ exact match

Three arguments: only the three-parameter version fits.

sum(7, 1, 2)arguments: int, int, intsum(int, int)✗ wrong countsum(double, double)✗ wrong countsum(int, int, int)✓ exact matcha = 7, b = 1, c = 2

a = 7, b = 1, c = 2.

sum(7, 1, 2)arguments: int, int, intsum(int, int)✗ wrong countsum(double, double)✗ wrong countsum(int, int, int)✓ exact matchreturns 10

10 is returned and printed.

sum('A', 1)arguments: char, intsum(int, int)✓ 'A' → 65sum(double, double)✓ fits by wideningsum(int, int, int)✗ wrong count

(char, int): char can widen to both int and double; the compiler picks the most specific one, (int, int).

sum('A', 1)arguments: char, intsum(int, int)✓ 'A' → 65a = 65, b = 1sum(double, double)✓ fits by wideningsum(int, int, int)✗ wrong count

'A' → 65: a = 65, b = 1.

sum('A', 1)arguments: char, intsum(int, int)✓ 'A' → 65returns 66sum(double, double)✓ fits by wideningsum(int, int, int)✗ wrong count

66 is returned and printed. The choice is made at compile time, from the argument types alone.

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));
}

Methods Calling Methods

Methods Calling Methods

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);
    }
}
Output
25
  • A method can call another method.
  • A complex task is split into small pieces: sumOfSquares delegates the work to square and sum.
  • The code becomes readable and manageable; each piece can be tested on its own.
  • sum(square(num1), square(num2)) evaluates the arguments first (left to right), then makes the outer call.
3² + 4² = 9 + 16 = 25.

Methods Calling Methods · Step-by-step code trace

sumOfSquares(3, 4): The Call Stack

Stackmain()result?

main calls sumOfSquares(3, 4).

StacksumOfSquares(3, 4)num13num24main()result?

sum needs its arguments before it can be called: first square(num1).

Stacksquare(3)num3sumOfSquares(3, 4)num13num24main()result?

A third frame is pushed: square(3) → 3 × 3 = 9 is returned.

StacksumOfSquares(3, 4)num13num24main()result?

square's frame is popped; the first argument (arg1) = 9. Next: square(num2).

Stacksquare(4)num4sumOfSquares(3, 4)num13num24main()result?

square(4) → 4 × 4 = 16 is returned.

Stacksum(9, 16)num19num216sumOfSquares(3, 4)num13num24main()result?

The arguments are ready: sum(9, 16) is called → 25. Here num1 = 9; sumOfSquares's is still 3.

StacksumOfSquares(3, 4)num13num24main()result?

sum's result becomes sumOfSquares's return value: 25 is returned.

Stackmain()result25

Back in main: result = 25.

Stackmain()result25

The screen shows 25. At most 3 frames were on the stack at once.

static int square(int num) {
  return num * num;
}
static int sum(int num1, int num2) {
  return num1 + num2;
}
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);
}

Built-in Methods

The Most Common Methods (Java API)

AreaClassesExample methodsPackage
Console outputSystem.outprint, println, printfjava.lang
MathMathsqrt, abs, max, powjava.lang
TextStringlength, charAt, substring, equalsjava.lang
ArraysArrayssort, copyOf, binarySearch, equalsjava.util
User inputScannernextInt, nextLine, closejava.util
FilesFile, FileWritercreateNewFile, write, closejava.io
DatabasesDriverManager, StatementgetConnection, executeQuery, executeUpdatejava.sql
Data structuresArrayListadd, remove, get, sizejava.util
TimeLocalDateTime, DateTimeFormatternow, ofPattern, formatjava.time
Web / graphicsURI, URL, JFrameURI.create, openConnection, setVisiblejava.net, javax.swing

java.lang is imported automatically; the others need an import, e.g. import java.util.Scanner;

Built-in Methods

Printing to the Screen

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);
    }
}
Output
Hello, World!
One line
Age: 20
Pi is about 3,14
  • System.out.println(x): prints x and moves to the next line.
  • System.out.print(x): prints x and stays on the same line.
  • + joins text and values: "Age: " + age.
  • printf: formatted output; %.2f 2 decimal places, %d integer, %s text, %n line break.
  • printf uses the locale: on a Turkish system the decimal separator is a comma (3,14).

Built-in Methods

The Math Class

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));
  • The Math class holds math operations; its methods are static, so they are called as Math.sqrt(16).
  • Math.max(3, 5) returns int 5; stored in a double variable, it becomes 5.0.
  • sqrt and pow always return double.
Output
4.0
17.2
5.0
1024.0
3
-4
5

Scope

Local Variables

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
}
error: cannot find symbol
        System.out.println(result);
                           ^
  symbol:   variable result
while multiply(2, 3) runsmultiplynum1=2 num2=3result=6otherMethodafter returnpoppedotherMethod
  • A local variable is declared inside a method or block; parameters are local too.
  • It exists only while the method runs; it cannot be accessed from outside the method.
  • result exists only while multiply runs; it disappears when the method returns.
  • The way to carry a value out is return: int s = multiply(2, 3);

Scope

Scope

Scope is the region of code where a variable is declared and can be used.

  • Every variable has a scope: in Java, it is the brace-delimited block.
  • Scope determines a variable's accessibility and lifetime.
  • Local and global scopes have different access rules.
  • In nested scopes, the inner scope can access the outer scope's variables; the outer scope cannot see the inner one.
  • Using the same name in different scopes can lead to name clashes; misused scope causes bugs.
class Example (class scope) field: globalVar void method() (method scope) outerVar { ... } (block scope) innerVar sees: innerVar, outerVar, globalVar

Scope

Local and Global Scope

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 visible here
            System.out.println(outerVar + innerVar
                    + globalVar);
        }
        // innerVar does NOT exist here
    }
    public static void main(String[] args) {
        method();
    }
}
Output
25

10 + 5 + 10 = 25: the inner block sees both the method's and the class's variables.

class: globalVarmethod(): outerVarblock: innerVarsees all three
Local scope

Inside a method or block; lives as long as that block runs.

Global scope

Accessible everywhere, lives for the whole program. In Java, class fields play this role.

Nested scope

A scope within a scope; the inner one can access the outer one's variables.

Scope

Name Clashes

Same name inside a block: error

public void method() {
    int outerVar = 10;
    {
        int outerVar = 5;  // ERROR
    }
}
error: variable outerVar is already
       defined in method method()

Java does not allow it.

A local variable shadows a field

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);
    }
}
Output
5
10
10

The local value shadows the field with the same name; the field is reached as Shadow.value.

Scope · Step-by-step code trace

Shadowing: Tracing the Code

class fieldShadow.value = 10main

The class field value = 10 is created when the program starts and lives as long as it runs. main calls show().

class fieldShadow.value = 10mainshow

show gets a new frame; it has no local variables yet.

class fieldShadow.value = 10mainshowvalue = 5

The local value = 5 is declared. Inside this method the name now means the local: the field is shadowed.

class fieldShadow.value = 10mainshowvalue = 5value → local 5

value is looked up in the innermost scope first → the local 5 is printed.

class fieldShadow.value = 10mainshowvalue = 5Shadow.value → 10

Shadow.value uses the class name to reach the field → 10.

class fieldShadow.value = 10mainvalue → field 10

show has ended; the local value is gone. main has no local value: the name means the field → 10.

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);
    }
}

Scope · Step-by-step code trace

When Are Variables Born, and When Do They Die?

Memorymain()static fieldscallCount0

The class field callCount is created when the program starts and lives as long as it runs. multiply(2, 3) is being called.

Memorymultiply(2, 3)num12num23main()static fieldscallCount1

The method can access the class field: callCount becomes 1.

Memorymultiply(2, 3)num12num23result6main()static fieldscallCount1

The local result is born now: 6.

Memorymain()first6static fieldscallCount1

multiply returned: num1, num2, result are gone. The value was assigned to first.

Memorymultiply(6, 4)num16num24result24main()first6static fieldscallCount2

New frame: result = 24, counter 2.

Memorymain()first6second24static fieldscallCount2

second is a local variable that lives only inside the inner block.

Memorymain()first6second24static fieldscallCount2

Inside the block, second is accessible: 24 is printed.

Memorymain()first6static fieldscallCount2

The block ended, and second is gone: 6 2.

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);
}

Abstraction and Design

Abstraction

Abstraction means ignoring details to reduce complexity.

16 Math.sqrt how does it compute? (hidden detail) 4.0 what did I give? what did I get?
Why?

It makes code more readable and simpler; it keeps large, complex programs understandable.

How?

It splits code into pieces that can be thought about separately. Whoever uses a method doesn't need to know its insides.

Everyday analogy: you don't need to know how the engine works to drive a car; the wheel and pedals are an "interface".

Abstraction and Design

Procedural Abstraction

Abstraction over computations, a.k.a. functional or procedural abstraction.

  • What matters is what a method computes, not how it computes it.
  • As long as you know its job, you don't care how it does it.
  • You don't worry about the method's implementation (its body).
  • Even if the body changes (say, a faster algorithm), the calling code stays the same.
System.out.println("Hello");

The method prints the given text to the console; you don't need to know how (character encoding, OS calls…).

// the caller only knows the signature:
static boolean isPrime(int num)
// "returns true if num is prime"
if (isPrime(17)) { ... }
17isPrimebody hiddentruethe user knows only the input and output

Abstraction and Design

Generalization

Context:

  • how a number relates to the other parts of an equation,
  • how a word's meaning depends on its place and role in a sentence,
  • the state and interactions inside a block of code.

The meaning of an expression can depend on the words around it.

Generalization:

  • adapting a solution from one context to fit others,
  • making a product more general and versatile.

In code, the tool for generalization is the parameter: fixed values become parameters.

public class Generalization {
    // specific: prints exactly 10 '-'
    static void drawLine() {
        System.out.println("----------");
    }
    // general: length and character as 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, '=');
    }
}
Output
----------
*****
============

Abstraction and Design

Decomposition

Breaking a problem into small pieces (decomposition) is a basic step in programming. Each piece becomes a method, so the code is organized, readable, reusable and maintainable.

main (grade program) readGradesinput computeAverageprocess letterGradedecision
// readGrades and letterGrade are separate methods too
static double computeAverage(int[] grades) {
    int sum = 0;
    for (int n : grades) {
        sum += n;
    }
    return (double) sum / grades.length;
}
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));
}
Output (input: 80 90 75)
Average: 81.66666666666667 -> BB

main reads like a table of contents: you see what is done, and how it is done lives in the helper methods.

Abstraction and Design

When to Write a Method?

A rule of thumb: DRY (Don't Repeat Yourself). The moment you feel like copying and pasting code, that code is a candidate for a method.

Repeated code

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, every copy
// must be fixed separately

With a method

static 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));
Output
80.0
71.66666666666667

This matters for reuse and easy maintenance. A good method does one thing and is easy to read.

Abstraction and Design

Good Method Design

Single responsibility

Each method should do one thing. If you describe it with "and" (read and compute and print), split it.

Descriptive name

A verb that says what it does: computeAverage, isPrime, readGrades. doStuff2 and similar names say nothing.

Parameters

Take the data you need as parameters; don't secretly depend on outside variables. Few parameters read better.

Return value

Return the result explicitly with return. A method that computes shouldn't print; let the caller do the printing.

Short and focused

Methods of a few lines that fit on one screen are easy to understand and test.

Call where needed

Call a method only where you need it; recomputing the same result again and again in a loop is wasted work.

Abstraction and Design

Naming Variables

Each variable should represent one thing

  • A variable should hold a single object or piece of data; using the same variable first for an age and then for a total is confusing.
  • This makes code more readable and reusable, and reduces logic errors.

A good name

  • Is descriptive and meaningful; reflects the nature of the data it stands for.
  • Says what the variable holds and how it is used; meaningless or one-letter names hurt readability (the loop counter i and the mathematical x are exceptions).
  • Java convention: camelCase (studentCount), classes capitalized (Book), constants MAX_SIZE.
int studentCount;      // a good name
int a;                  // a meaningless name
int age = 25;
String name = "Ahmet";
double average = 85.5;
String bookTitle;
BadGood
int x1, x2;int midtermGrade, finalGrade;
double d;double circleArea;
boolean f;boolean isPrime;

Summary

Summary

TopicKey points
Definitionaccess [static] returnType name(parameters) { body }; signature = name + parameter types
Callarguments are copied into parameters (pass by value); each call pushes a new frame on the stack
return / voidreturn hands back a value and ends the method; void returns no value
staticstatic methods directly / ClassName.method(); otherwise object.method()
Overloadingsame name, different parameter lists; chosen at compile time
Built-in methodsSystem.out, Math (static: Math.sqrt(16)); java.lang is automatic; others need import
Scopea variable lives in the block that declares it; inner blocks see outer ones, not the reverse; fields live for the whole program
Designabstraction (what, not how), generalization (parameters), decomposition, DRY, single responsibility

Summary

Common Mistakes (1)

Calling a non-static method from mainnon-static method add(int,int) cannot be referenced from a static contextFix: make the method static, or create an object and call it on that.
Forgetting return on some pathsmissing return statementIn an if/else if chain every case must end with a return; put a default return at the end.
Using the result of a void methodincompatible types: void cannot be converted to intint x = greet(); doesn't work: a void method produces no value.
Missing / extra argumentsmethod add in class ... cannot be applied to given types; required: int,int found: intThe number and types of arguments must match the signature.

Summary

Common Mistakes (2)

Using a local variable outside its methodcannot find symbol … variable resultReturn the value with return.
Same variable name in an inner blockvariable outerVar is already defined in method method()
Expecting a swap method to workswap(int x, int y) only swaps the copies; after swap(arr[0], arr[2]) the array is unchanged. For array cells use swap(int[] d, int i, int j).
Overloading by return typeint f(int a) and double f(int a) cannot coexist: method f(int) is already defined. Only the name and parameter types make up the signature.
Expecting the argument to changeincrease(num) leaves num unchanged: the copy changes. Return the new value with return.
Forgetting Math's result typeint k = Math.sqrt(16); → possible lossy conversion from double to int. sqrt and pow return double.

Summary

Practice Problems (1)

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); }
// in main:
System.out.println(cube(2) + square(3));
  1. What does the program on the left print? Why didn't a change?
  2. What does the line on the right print? At most how many frames are on the stack while cube(2) runs (including main)?
Show answers
  1. 3 7 and 7. f doubles a copy of a; a stays 3. f(f(1)) = f(3) = 7.
  2. 8 + 9 = 17. main → cube(2) → square(2): at most 3 frames.

Summary

Practice Problems (2)

static int sum(int a, int b) { return a + b; }
static double sum(double a, double b) { return a + b; }
// in 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)));
  1. In the first two println calls, which sum method runs, and what is printed?
  2. Why does the last line not print 8 but 8.0?
Show answers
  1. sum(2, 3.0) → the double version (2 is widened to double): 5.0; sum(2, 3) → the int version: 5.
  2. Math.sqrt returns a double; max(int, double) picks the double version: 8.0.

Summary

Exercises

  1. boolean isEven(int num): return true if the number is even.
  2. int largest(int a, int b, int c): find the largest of three numbers with Math.max.
  3. int power(int base, int exp): compute the power with a loop (without Math.pow).
  4. int digitSum(int n): sum the digits of a number with a loop.
  5. double circleArea(double r) — write it, then print the result with printf to 2 decimal places.
  6. Overloaded double area(double r) (circle) and double area(double width, double height) (rectangle).
Answers / hints
  1. return num % 2 == 0; → isEven(7) = false, isEven(10) = true.
  2. return Math.max(a, Math.max(b, c)); → largest(4, 9, 2) = 9.
  3. int result = 1; for (int i = 0; i < exp; i++) result *= base; return result; → power(2, 10) = 1024.
  4. while (n != 0) { t += n % 10; n /= 10; } → digitSum(2024) = 8.
  5. return Math.PI * r * r; → printf("%.2f%n", circleArea(2)) → 12,57.
  6. area(1) → 3.14159…; area(3, 4) → 12.0. The number of arguments decides which version is called.

Summary

References

  • 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 (Chapter 8.4 Method Declarations, 6.3 Scope).
  • 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).

The End

Chapter 3.2: Methods
Previous: Chapter 3.1: Control Structures · Next: Chapter 3.3: Arrays
1 / 1 Sercan KÜLCÜ. All rights reserved.