• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Syntax Fundamentals
  3. Methods and Functions
  4. Return Values

      Return Values

      Return Values

      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.

      The return Keyword

      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.

      Every Path Must Return

      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
      }
      

      Void Methods

      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);
      }
      

      Using the Returned Value

      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.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In