4.1.1.10–4.1.1.12 - Subroutines, parameters and return values (Java)
Learn how named methods split a Java program into manageable jobs, how arguments supply their inputs and how a returned value supplies a result. These ideas let one calculation serve many callers without copying its source. This Java route is incomplete: runnable support pending; the examples and code questions here are written practice with no Run.
Procedures and functions
A subroutine is a named block of code defined separately from the statements that call it. Calling its name transfers control to that block; when it finishes, control returns to the caller. A Java subroutine is a method. It must be declared inside a class, even when we organise a program procedurally using static methods.
Procedure and function
A procedure performs a task without returning a result value; a function returns a value for its caller to use. Java declares a no-result method with void, and a value-returning method with its result type.
This complete program calls a procedure twice:
public class Main {
static void printBorder() {
System.out.println("-----");
}
public static void main(String[] args) {
printBorder();
System.out.println("Scores");
printBorder();
}
}
Its output is -----, then Scores, then -----, on separate lines. The method declaration does not print anything merely by being present. Each call executes its body. The next statement in main resumes after that particular call, so both calls use the same method without sharing a single return position.
Named jobs make a caller readable: printBorder() expresses an intention. One definition avoids duplicated code; a corrected border is then used by every call. A small method can also be tested separately and reused in another context. Decomposition is useful when each method has a clear responsibility; splitting every single statement into a method would add clutter instead.
Interfaces and parameters
A method's interface tells the caller what to supply and what to expect: its name, parameter types and order, return type, and any input assumptions or effects. This use of “interface” means a subroutine contract; it does not require a Java interface declaration.
In static int ticketCost(int adults, int children), adults and children are formal parameters. In ticketCost(3, 2), the expressions 3 and 2 are arguments or actual parameters. Arguments are evaluated by the caller and their values initialise the parameters. Swapping the order may change the meaning even when both have type int. A clear contract might require non-negative counts and promise a cost in whole pounds.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account