Methods in Java

A method groups a piece of behaviour behind a name, a parameter list and a return type, and that signature is the contract callers depend on.

What a method is

A method is a named block of code that takes zero or more inputs and optionally produces a result. It is the smallest unit of reuse in Java, and the place where a program stops being a list of statements and starts being a design.

Why methods exist

  • The same logic is written once and called from many places.
  • A good name replaces a comment, because the call site reads as a sentence.
  • The body can be changed without touching any caller, as long as the signature holds.
  • Small units can be tested independently.

Syntax

modifiers returnType methodName(parameterList) throws ExceptionTypes {
    body
}
public double averageOf(int[] values) {
    if (values.length == 0) {
        return 0;
    }
    int total = 0;
    for (int value : values) {
        total += value;
    }
    return (double) total / values.length;
}

The parts of a declaration

PartMeaning
ModifiersVisibility such as public, plus static, final, abstract and others.
Return typeThe type of the value produced, or void for none.
Method namelowerCamelCase, normally a verb phrase.
Parameter listTyped placeholders for the inputs. May be empty.
throws clauseThe checked exceptions a caller must deal with.
The signature is the method name plus the parameter types, in order. The return type is not part of it, which is why two methods cannot differ by return type alone.

Parameters and arguments

A parameter is the variable in the declaration. An argument is the actual value supplied at the call. The words are often swapped in conversation, but the distinction matters when reading error messages.

public int discountedPrice(int price, int percent) {   // parameters
    return price - (price * percent / 100);
}

int payable = discountedPrice(2000, 15);               // arguments

Return values

public boolean isEligible(int age) {
    return age >= 18;          // every path must return a value
}

public void log(String message) {
    if (message == null) {
        return;                // a bare return exits a void method early
    }
    System.out.println(message);
}

A method with a non void return type must return on every reachable path, and the compiler checks it. Code after an unconditional return is unreachable and will not compile.

Instance methods and static methods

public class Circle {

    private final double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double area() {                       // instance method, uses state
        return Math.PI * radius * radius;
    }

    public static double areaOf(double radius) { // static, depends on inputs only
        return Math.PI * radius * radius;
    }
}

An instance method needs an object because it reads or changes that object. A static method belongs to the class and is called as Circle.areaOf(4). If a method never touches instance state, making it static states that fact clearly.

Scope

public class Counter {

    private int total = 0;          // field: visible throughout the class

    public void add(int amount) {   // parameter: visible in this method
        int doubled = amount * 2;   // local: visible from here to the closing brace

        if (doubled > 100) {
            int excess = doubled - 100;   // visible only inside this block
            total += excess;
        }
        // excess is no longer in scope here
        total += doubled;
    }
}
  • A local variable lives from its declaration to the end of the enclosing block.
  • A parameter behaves like a local variable of the method.
  • A local variable may shadow a field of the same name; this.total reaches the field regardless.

Common mistakes

  • Declaring a return type and then forgetting to return on one branch.
  • Writing a method that both changes state and returns a value, so callers cannot tell what it does from its name.
  • Passing a long list of positional parameters where a small object would be clearer.
  • Leaving a method public when nothing outside the class calls it.

Best practices

  • One method, one responsibility. If the name needs the word and, split it.
  • Keep parameter lists short. Three or four is usually the practical limit.
  • Validate arguments at the start and fail fast with a clear message.
  • Give the method the narrowest visibility that still works.
  • Prefer returning a value over changing a parameter, because it is far easier to reason about.

Practice

  1. Write a method that returns the larger of two numbers without using Math.max.
  2. Why will int f() { if (x) return 1; } not compile?
  3. Convert a method that prints a formatted invoice line into one that returns the line as a String. What does that make easier to test?
  4. Given a method that both saves a record and returns a count, split it into two and explain the improvement.

Conclusion

A method is a contract: a name, the inputs it accepts and the result it promises. Keep that contract small and honest, and the rest of the design tends to follow.

Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All Java notes →
Java

Recursion in Java

A recursive method calls itself on a smaller problem, and it works only when a base case guarantees the shrinking stops.

Read more
Java

Varargs in Java

A variable arity parameter lets a method accept any number of arguments, and inside the method it is simply an array.

Read more
Java

Pass by Value in Java

Java always passes arguments by value. For objects the value copied is the reference, which explains every result that looks like pass by reference.

Read more

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.