Returning from branches
A method can have several return statements, one in each branch. The first return that runs ends the method:
public class Main {
public static void main(String[] args) {
System.out.println(result(72));
System.out.println(result(35));
}
public static String result(int points) {
if (points >= 50) {
return "pass";
}
return "fail";
}
}
pass
failFor 72 the first return runs, and the method ends there. For 35 the if is skipped and the second return runs. No else is needed, because the method never gets past a return.
Java checks that every way through the method ends in a return. Without the last line, the method has no value to give back when the points are below 50, and it doesn't compile:
public class Main {
public static void main(String[] args) {
System.out.println(result(72));
}
public static String result(int points) {
if (points >= 50) {
return "pass";
}
}
}
Main.java:10: error: missing return statement
}
^
1 error