Methods: parameters and return values
Until now all your code lived inside main. When a program grows, this becomes unmanageable: you repeat the same lines in several places and any change forces you to touch many spots. A method is a named block of code that you can call as many times as you want. Dividing a program into small methods, each with a clear task, is the number one tool to keep code readable, test it in parts and reuse it.
Anatomy of a method
A method has a signature and a body. The signature includes the modifier (for now public static), the return type, the name and the parameter list between parentheses. The return type says what the method gives back: int, String, boolean... or void if it returns nothing. If the type is not void, the body must end every possible path with return followed by a value of that type. Parameters are variables that receive the values passed by the caller; those concrete values are called arguments. By convention method names are in camelCase and start with a verb: calculateTotal, isPrime, printReport.
public class Main {
// No parameters, no return value
static void greet() {
System.out.println("Hello!");
}
// One parameter, no return value
static void greetPerson(String name) {
System.out.println("Hello, " + name + "!");
}
// Two parameters, returns an int
static int add(int a, int b) {
return a + b;
}
// Returns a boolean: a good name reads like a question
static boolean isEven(int number) {
return number % 2 == 0;
}
// Several return paths: every path must return something
static String classify(int age) {
if (age < 13) {
return "child";
} else if (age < 18) {
return "teenager";
}
return "adult";
}
public static void main(String[] args) {
greet();
greetPerson("Ana");
int result = add(3, 4); // result = 7
System.out.println(result);
System.out.println(add(add(1, 2), 10)); // 13: calls can be nested
System.out.println(isEven(10) + " " + isEven(7));
System.out.println(classify(15));
}
}Passing arguments: by value
Java always passes arguments by value: the method receives a copy. With primitive types this means that if the method modifies its parameter, the original variable does not change. With objects and arrays what is copied is the reference, that is, the address of the object; that is why the method can change the content of an array or list it receives, although it cannot make the original variable point to another object. This is a point that confuses almost everyone at first, so let us test it.
import java.util.Arrays;
public class Main {
static void tryToChange(int x) {
x = 100; // changes only the local copy
}
static void changeContent(int[] data) {
data[0] = 100; // changes the shared array
}
static void replaceArray(int[] data) {
data = new int[] {9, 9}; // only the local reference changes
}
// Methods help avoid repeating code
static double average(int[] values) {
if (values.length == 0) return 0; // early return for a special case
int sum = 0;
for (int v : values) sum += v;
return (double) sum / values.length;
}
public static void main(String[] args) {
int number = 5;
tryToChange(number);
System.out.println(number); // 5
int[] array = {1, 2, 3};
changeContent(array);
System.out.println(Arrays.toString(array)); // [100, 2, 3]
replaceArray(array);
System.out.println(Arrays.toString(array)); // [100, 2, 3]
System.out.println(average(new int[] {4, 8, 6})); // 6.0
System.out.println(average(new int[] {})); // 0.0
}
}- Forgetting the return in one path of the method: the compiler warns with missing return statement.
- Writing return with a value in a void method: it is not allowed; only return; with no value.
- Calling a method and discarding the result when you needed it: add(2, 3); stores nothing.
- Making a method print instead of return: returning the value is more reusable, because the caller decides what to do with it.
- Giant methods: if a method does not fit on one screen or does several things, split it.
Testez vos acquis
Question 1 sur 1Which return type do you use if the method returns nothing?
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères