Your own methods
What you'll learn:
- write your own methods with parameters and
returnand call them frommain; - explain why a method cannot change a variable you pass to it;
- predict which of several methods with one name the compiler picks;
- trace a recursive method through the call stack.
Picture a blender in the kitchen. You put food into the jar, press the button and get a smoothie. To make another one, nobody builds a new blender: you put other food into the jar and press the button again.
In a program, a method plays the part of that appliance. You already write one method in every program, main. But you can add your own methods to the class as well.
Why? If a program needs the same calculation five times, without a method you would write it five times. A bug in it would then have to be fixed in five places.
A method is written once and called as often as you like. Here is a method that squares a number:
public class Main {
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
System.out.println(square(3)); // 9
System.out.println(square(5)); // 25
int total = square(2) + square(4);
System.out.println(total); // 20
}
}Let's walk through the program step by step:
- The method
squareis declared inside the classMain, next tomain, not inside it. - As always, the program starts in
main.square(3)is a call:mainhands the number3to the method and waits for the answer. - Inside
squarethe variablexis3, andreturn x * x;returns9. - The
9takes the place of the callsquare(3), andprintlnprints it. - The call
square(5)works the same way and gives25. - In the line
int total = square(2) + square(4);the two calls give4and16, sototalgets20.
The method header
The first line of the method, static int square(int x), is its header. It says how to call the method and what it returns. Let's read it from left to right:
static, as onmain: the method belongs to the classMainitself, somaincalls it by name:square(3);intis the result type: the method returns a whole number;squareis the method's name; it is written like a variable name, starting with a lowercase letter:square,findMax;(int x)is a parameter: a variable of the method that gets a value when the method is called.
After the header comes the method's body in curly braces: the statements that run on every call.
Parameters and arguments are often mixed up, and interviewers tell them apart:
- a parameter is the variable in the header:
xinsquare(int x); - an argument is the value passed in a call:
3insquare(3).
A method can take several parameters, separated by commas: static int max(int a, int b). A call then passes as many arguments, in the same order: max(3, 7).
The order of methods in a class does not matter: square could also be written below main. A method does not run where it is written; it runs when it is called.
Here the blender picture is off. You can switch a blender on with an empty jar, but you cannot call a method that has a parameter without an argument: for square() the compiler answers method square in class Main cannot be applied to given types.
The return statement
The return statement does two things:
- it hands a value back to the place of the call;
- it ends the method at once: the lines after it do not run.
The value after return must fit the result type: a method of type int cannot return the string "hi".
The compiler checks return strictly. A method with a result type must return a value on every path through it. The check happens before the program runs, so it does not matter which arguments the method is actually called with. The compiler does not evaluate conditions, so to it an if without a final else always has a path around it, even when your conditions cover every number.
void methods
Not every method calculates something. Sometimes it only performs an action, such as printing. Then you write void in place of the result type, as on main:
public class Main {
static void greet(String name) {
System.out.println("Hi, " + name);
}
public static void main(String[] args) {
greet("Anna"); // Hi, Anna
greet("Bob"); // Hi, Bob
}
}What matters about void methods:
- they never contain
returnwith a value, andreturn;with no value ends the method early; - a call to such a method stands as a statement of its own:
int n = greet("Anna");does not compile, because the call has no value.
Variables inside a method
A method's parameters and the variables declared in its body are local. They appear when the method is called and disappear when it finishes. Other methods cannot see them:
maincannot readxfromsquare: the compiler answerscannot find symbol;squaredoes not see the variables ofmain;- so two methods can each have a variable with the same name, and these are two different variables.
A blender does not know what is in your fridge either: it works only with what was put into the jar.
Common mistake
The method returns a value on some paths only:
static int abs(int x) {
if (x < 0) {
return -x;
}
} // ✗error: missing return statementThe program does not compile. When x is not negative, the method reaches its closing brace without meeting a return. The compiler checks every path, not only the one your call takes, so the error appears even if you only ever call abs(-5). Add return x; before the method's closing brace.
Key points
- A method is declared in the class next to
main:static, the result type, the name, the parameters and the body —static int square(int x) { return x * x; }. - A call puts the arguments into the parameters, and
returnhands a value back to the place of the call and ends the method. - A method with a result type must return a value on every path, or the program does not compile:
missing return statement. - A
voidmethod returns nothing; a method's parameters and variables are visible only inside it.