GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java6 / 25

Methods

Separating decisions, calculations, and side effects

5.1 Learning objectives

By the end of this chapter, you should be able to:

  • identify a method’s parameters, return type, and body;
  • extract responsibilities out of the main method;
  • distinguish computation from input and output;
  • understand pass-by-value argument passing;
  • use overloading without introducing ambiguity.

5.2 Small, clear contracts

A method’s contract turns arguments into a result.

Figure 5.1. A method’s contract turns arguments into a result.

The signature communicates what a method takes in and gives back:

public static int add(int first, int second) {
    return first + second;
}

Names should express intent. normalizeCommand is more informative than process.

5.3 Refactoring the chatbot

import java.util.Locale;

public class Chapter05Methods {
    public static String normalizeCommand(String input) {
        if (input == null) {
            return "";
        }
        return input.strip().toLowerCase(Locale.ROOT);
    }

    public static String respond(String input) {
        String command = normalizeCommand(input);

        return switch (command) {
            case "hi" -> "Hello!";
            case "help" -> "Commands: hi, help, tip, and exit.";
            case "tip" -> "A method should have one main responsibility.";
            case "exit" -> "See you soon!";
            case "" -> "Enter a message.";
            default -> "I did not understand. Type help.";
        };
    }

    public static boolean shouldExit(String input) {
        return normalizeCommand(input).equals("exit");
    }

    public static void main(String[] args) {
        System.out.println(respond("  TIP "));
    }
}

normalizeCommand and respond are deterministic: for the same input, they always return the same output. This makes testing easy. main is left responsible only for coordinating execution and printing results.

5.4 Scope and pass-by-value

Comic: the do-everything method.

Figure 5.2. Comic: the do-everything method.

Local variables exist only inside the block where they were declared. Java always passes arguments by value. For primitive types, the value itself is copied; for objects, the copied value is the reference. A method can modify the object pointed to by that reference, but it cannot reassign the caller’s original variable.

public static void increment(int number) {
    number++;
}

After calling increment(value), the caller’s value variable remains unchanged.

5.5 Overloading

Overloading allows multiple methods with the same name and different parameter lists:

public static int calculateTotal(int a, int b) {
    return a + b;
}

public static double calculateTotal(double a, double b) {
    return a + b;
}

The return type alone does not distinguish two overloads.

5.6 Validation and exceptions

A method should reject values that violate its contract:

public static double calculateAverage(double sum, int count) {
    if (count <= 0) {
        throw new IllegalArgumentException("Count must be positive.");
    }
    return sum / count;
}

Throwing an exception makes the failure explicit. Later, you will decide where to catch it.

5.7 Project evolution: version 5

The chatbot flow is now divided into three reusable decisions:

  • normalizing input;
  • producing a response;
  • deciding whether the conversation should end.

The complete example is in examples/src/Chapter05Methods.java.

5.8 Verifiable practice

  1. Create isKnownCommand(String).
  2. Create welcomeMessage(String name).
  3. Rewrite the loop from the previous chapter using these methods.

Test cases for normalizeCommand:

InputReturn value
" HELP ""help"
""""
null""

Mastery check

The main method should read like an outline. If it holds all the rules, there are still responsibilities left to extract.