Parameters and return values
A method becomes really useful when it takes data and gives back a result. Data comes in through parameters, and the result goes out with the return statement.
Parameters
Parameters are listed in the parentheses of the declaration: a type and a name, like a variable. The value passed in a call is called an argument:
void greet(String name) {
IO.println("Hello, " + name + "!");
}
void main() {
greet("Anna");
greet("Oleg");
}Output:
Hello, Anna!
Hello, Oleg!Inside the method the parameter name works like a regular variable that already holds the argument's value. The number and types of arguments must match the parameters, otherwise the program does not compile.
Several parameters
Parameters are separated by commas, and each has its own type. Arguments are passed in the same order:
void printPrice(String item, double price, int quantity) {
IO.println(item + ": $" + price * quantity);
}
void main() {
printPrice("Cappuccino", 3.5, 2);
}Output:
Cappuccino: $7.0Returning a value
Instead of void, write the result type, and in the body write return with a value. A call to such a method becomes a value itself — you can store it in a variable or use it right away:
int square(int n) {
return n * n;
}
void main() {
int result = square(5);
IO.println(result);
IO.println(square(3) + square(4));
}Output:
25
25return ends the method
return leaves the method immediately — code after it does not run. That is why a method can have several return statements in different branches:
String grade(int score) {
if (score >= 90) {
return "Excellent";
}
if (score >= 60) {
return "Pass";
}
return "Fail";
}
void main() {
IO.println(grade(95));
IO.println(grade(40));
}Output:
Excellent
FailIn a void method you can write return; without a value to leave early.
Passing by value
Java passes a copy of the argument's value into the method. If the method changes a parameter of a primitive type, the variable outside stays the same:
void addBonus(int points) {
points += 100;
IO.println("Inside the method: " + points);
}
void main() {
int points = 50;
addBonus(points);
IO.println("Outside: " + points);
}Output:
Inside the method: 150
Outside: 50To get the new value, return it with return and assign it: points = addBonus(points).
Common mistake
If a method declares a result type, a return must be reached on every path. Here the method would return nothing for a negative n:
String sign(int n) {
if (n >= 0) {
return "plus";
}
}
void main() {
IO.println(sign(5));
}Output:
Main.java:5: error: missing return statement
}
^
1 error
error: compilation failedAdd a return at the end of the method or an else branch so a value is always returned.