Newer Version Available
Class Methods
- Optional: Modifiers, such as public or protected.
- Required: The data type of the value returned by the method, such as String or Integer. Use void if the method does not return a value.
- Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in parentheses (). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters.
- Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable declarations, is contained here.
As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable.
- Can be used anywhere that system methods are used.
- Can be recursive.
- Can have side effects, such as DML insert statements that initialize sObject record IDs. See Apex DML Statements.
- Can refer to themselves or to methods defined later in the same class or anonymous block. Apex parses methods in two phases, so forward declarations are not needed.
- Can be polymorphic. For example, a method named foo can be implemented in two ways, one with a single Integer parameter and one with two Integer parameters. Depending on whether the method is called with one or two Integers, the Apex parser selects the appropriate implementation to execute. If the parser cannot find an exact match, it then seeks an approximate match using type coercion rules. For more information on data conversion, see Understanding Rules of Conversion.
- When using void methods that have side effects, user-defined methods
are typically executed as stand-alone procedure statements in Apex code. For example:
- Can have statements where the return values are run as a statement if their results are not assigned to another variable. This is the same as in Java.
Passing Method Arguments By Value
In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call and can't be changed to point to another object. However, the values of the object's fields can be changed in the method.
The following are examples of passing primitive and non-primitive data type arguments into methods.
Example: Passing Primitive Data Type Arguments
Example: Passing Non-Primitive Data Type Arguments