• Lessons Home
  1. Lessons
  2. Apex Syntax Fundamentals
  3. Getting Started with Apex
  4. Scope

      Scope

      Scope

      In Apex, scope determines the visibility and lifetime of a variable. Variables can have different scopes, such as local (within a method) or member (within a class).

      Example

      public class ScopeExample {
          // Member variable - accessible anywhere in this class
          private String memberVariable = "I am a member variable.";
      
          public void myMethod() {
              // Local variable - only accessible within this method
              String localVariable = "I am a local variable.";
      
              System.debug(memberVariable); // This is valid
              System.debug(localVariable); // This is also valid
          }
      
          public void anotherMethod() {
              System.debug(memberVariable); // This is valid
              // System.debug(localVariable); // This would cause a compile-time error
          }
      }
      
      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      Create an Account

      Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

      Create account

      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
      public class ScopeExample {
          // Member variable - accessible anywhere in this class
          private String memberVariable = "I am a member variable.";
      
          public void myMethod() {
              // Local variable - only accessible within this method
              String localVariable = "I am a local variable.";
      
              System.debug(memberVariable); // This is valid
              System.debug(localVariable); // This is also valid
          }
      
          public void anotherMethod() {
              System.debug(memberVariable); // This is valid
              // System.debug(localVariable); // This would cause a compile-time error
          }
      }