A method can send a result back to the code that called it. The type of that result is the return type, and it appears in the method signature right before the method name.
Inside the method body, the return keyword ends the method and hands a value back to the caller:
public static Integer convertHoursToMinutes(Integer hours) {
return hours * 60;
}
The return type here is Integer, so the method must return an Integer value.
If a method declares a non-void return type, every possible path through the method must return a value. If any branch can finish without returning, the code does not compile:
public static String checkTemperature(Integer degrees) {
if (degrees > 30) {
return 'Hot';
}
return 'Comfortable'; // needed so every path returns
}
A method with a return type of void returns nothing. It performs an action, such as logging, and simply ends:
public static void logMessage(String message) {
System.debug(message);
}
The caller can store the returned value in a variable and keep working with it:
Integer minutes = convertHoursToMinutes(2); System.debug(minutes); // 120
Return values are how methods communicate results. A method computes something once, and any caller can capture the answer and build on it.