Newer Version Available

This content describes an older version of this product. View Latest

Understanding Expressions

An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. In Apex, an expression is always one of the following types:

  • A literal expression. For example:
    11 + 1
  • A new sObject, Apex object, list, set, or map. For example:
    1new Account(<field_initializers>)
    2new Integer[<n>]
    3new Account[]{<elements>}
    4new List<Account>()
    5new Set<String>{}
    6new Map<String, Integer>()
    7new myRenamingClass(string oldName, string newName)
  • Any value that can act as the left-hand of an assignment operator (L-values), including variables, one-dimensional list positions, and most sObject or Apex object field references. For example:
    1Integer i
    2myList[3]
    3myContact.name
    4myRenamingClass.oldName
  • Any sObject field reference that is not an L-value, including:
    • The ID of an sObject in a list (see Lists)
    • A set of child records associated with an sObject (for example, the set of contacts associated with a particular account). This type of expression yields a query result, much like SOQL and SOSL queries.
  • A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example:
    1Account[] aa = [SELECT Id, Name FROM Account WHERE Name ='Acme'];
    2Integer i = [SELECT COUNT() FROM Contact WHERE LastName ='Weissman'];
    3List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];

    For information, see SOQL and SOSL Queries.

  • A static or instance method invocation. For example:
    1System.assert(true)
    2myRenamingClass.replaceNames()
    3changePoint(new Point(x, y));