Returning a value
The methods so far did their work and gave nothing back: they were void. A method can instead return a value to the code that called it. The value's type goes where void was, and a return statement says what to give back:
public class Main {
public static void main(String[] args) {
int weeks = 3;
int days = weeks * daysInWeek();
System.out.println(weeks + " weeks is " + days + " days");
System.out.println(daysInWeek());
}
public static int daysInWeek() {
return 7;
}
}
3 weeks is 21 days
7public static int daysInWeek()says the method returns anint.return 7;ends the method and hands 7 back to the call.- The call
daysInWeek()then stands for that value, anywhere a value can go: in a calculation, in a print line, or stored in a variable (int d = daysInWeek();).
A call whose value isn't used, like daysInWeek(); on a line of its own, runs the method, and the value is simply lost.
return ends the method
Nothing after a return runs, and Java refuses code that could never run:
public class Main {
public static void main(String[] args) {
System.out.println(daysInWeek());
}
public static int daysInWeek() {
return 7;
System.out.println("Counted the days");
}
}
Main.java:8: error: unreachable statement
System.out.println("Counted the days");
^
1 errorA void method can use a plain return; to stop early.