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

      Introduction to Methods

      Introduction to Methods

      A method is a named, reusable block of code that performs a specific task. Instead of writing the same logic over and over, you write it once inside a method and call the method by name whenever you need it.

      Anatomy of a Method

      Every method declaration has a few parts:

      • Access modifier — public or private, controls who can call the method
      • static — a static method belongs to the class itself, so you can call it without creating an object
      • Return type — the kind of value the method sends back, such as String or Integer (or void for nothing)
      • Name — a descriptive name written in camelCase
      • Parameter list — the inputs the method accepts, inside parentheses (this can be empty)
      • Body — the code between curly braces that runs when the method is called

      A Simple Example

      public static String getGreeting() {
          return 'Hello from Apex!';
      }
      

      This method is public, static, returns a String, is named getGreeting, and takes no parameters. The body returns a text value.

      Calling a Method

      To run a method, write its name followed by parentheses. If the method returns a value, you can store it in a variable:

      String message = getGreeting();
      System.debug(message); // Hello from Apex!
      

      Why Methods Matter

      • Reuse — write the logic once and call it from many places
      • Readability — a good method name explains what the code does
      • Testing — small, focused methods are easy to test on their own
      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