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:
    1 + 1
  • A new sObject, Apex object, list, set, or map. For example:
    new Account(<field_initializers>)
    new Integer[<n>]
    new Account[]{<elements>}
    new List<Account>()
    new Set<String>{}
    new Map<String, Integer>()
    new 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:
    Integer i
    myList[3]
    myContact.name
    myRenamingClass.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:
    Account[] aa = [SELECT Id, Name FROM Account WHERE Name ='Acme'];
    Integer i = [SELECT COUNT() FROM Contact WHERE LastName ='Weissman'];
    List<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:
    System.assert(true)
    myRenamingClass.replaceNames()
    changePoint(new Point(x, y));