0% found this document useful (0 votes)
60 views1,732 pages

Salesforce Apex Language Reference

Salesforce.com is a registered trademark of salesforce.com, inc. Other marks appearing herein may be trademarks of their respective owners. Introducing Apex. What is Apex?. How Does Apex Work?. Developing Code in the Cloud. What's New?.

Uploaded by

wawankn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views1,732 pages

Salesforce Apex Language Reference

Salesforce.com is a registered trademark of salesforce.com, inc. Other marks appearing herein may be trademarks of their respective owners. Introducing Apex. What is Apex?. How Does Apex Work?. Developing Code in the Cloud. What's New?.

Uploaded by

wawankn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1732

Version 31.

0: Summer 14

Force.com Apex Code Developer's Guide

Last updated: August 15, 2014


Copyright 20002014 salesforce.com, inc. All rights reserved. Salesforce.com is a registered trademark of salesforce.com, inc., as are other

names and marks. Other marks appearing herein may be trademarks of their respective owners.

Table of Contents

Table of Contents
Getting Started....................................................................................................................................1
Chapter 1: Introduction..............................................................................................................1
Introducing Apex..........................................................................................................................................................2
What is Apex?...............................................................................................................................................................2
When Should I Use Apex?............................................................................................................................................4
How Does Apex Work?................................................................................................................................................5
Developing Code in the Cloud.....................................................................................................................................6
What's New?.................................................................................................................................................................6
Understanding Apex Core Concepts.............................................................................................................................7

Chapter 2: Apex Development Process.......................................................................................12


What is the Apex Development Process?....................................................................................................................13
Using a Developer or Sandbox Organization..............................................................................................................13
Learning Apex.............................................................................................................................................................14
Writing Apex Using Development Environments......................................................................................................16
Writing Tests..............................................................................................................................................................17
Deploying Apex to a Sandbox Organization...............................................................................................................17
Deploying Apex to a Salesforce Production Organization..........................................................................................18
Adding Apex Code to a Force.com AppExchange App.............................................................................................18

Chapter 3: Apex Quick Start......................................................................................................19


Writing Your First Apex Class and Trigger................................................................................................................19
Creating a Custom Object...............................................................................................................................19
Adding an Apex Class.....................................................................................................................................20
Adding an Apex Trigger..................................................................................................................................21
Adding a Test Class.........................................................................................................................................22
Deploying Components to Production............................................................................................................24

Writing Apex.....................................................................................................................................25
Chapter 4: Data Types and Variables..........................................................................................25
Data Types..................................................................................................................................................................26
Primitive Data Types...................................................................................................................................................26
Collections...................................................................................................................................................................29
Lists.................................................................................................................................................................29
Sets..................................................................................................................................................................32
Maps................................................................................................................................................................32
Parameterized Typing......................................................................................................................................33
Enums.........................................................................................................................................................................34
Variables......................................................................................................................................................................36
Constants.....................................................................................................................................................................37
Expressions and Operators..........................................................................................................................................38
Understanding Expressions.............................................................................................................................38

Table of Contents

Understanding Expression Operators..............................................................................................................39


Understanding Operator Precedence...............................................................................................................44
Using Comments.............................................................................................................................................45
Assignment Statements...............................................................................................................................................45
Understanding Rules of Conversion............................................................................................................................46

Chapter 5: Control Flow Statements..........................................................................................48


Conditional (If-Else) Statements................................................................................................................................49
Loops...........................................................................................................................................................................49
Do-While Loops.............................................................................................................................................50
While Loops....................................................................................................................................................50
For Loops........................................................................................................................................................50

Chapter 6: Classes, Objects, and Interfaces.................................................................................53


Understanding Classes................................................................................................................................................54
Apex Class Definition.....................................................................................................................................54
Class Variables.................................................................................................................................................55
Class Methods.................................................................................................................................................56
Using Constructors..........................................................................................................................................58
Access Modifiers..............................................................................................................................................59
Static and Instance...........................................................................................................................................60
Apex Properties...............................................................................................................................................63
Extending a Class............................................................................................................................................66
Extended Class Example.................................................................................................................................67
Understanding Interfaces.............................................................................................................................................70
Custom Iterators..............................................................................................................................................71
Keywords.....................................................................................................................................................................73
Using the final Keyword..................................................................................................................................74
Using the instanceof Keyword.........................................................................................................................74
Using the super Keyword.................................................................................................................................74
Using the this Keyword...................................................................................................................................75
Using the transient Keyword...........................................................................................................................76
Using the with sharing or without sharing Keywords......................................................................................77
Annotations.................................................................................................................................................................78
Deprecated Annotation...................................................................................................................................78
Future Annotation...........................................................................................................................................79
IsTest Annotation...........................................................................................................................................80
ReadOnly Annotation.....................................................................................................................................83
RemoteAction Annotation..............................................................................................................................83
TestVisible Annotation...................................................................................................................................84
Apex REST Annotations................................................................................................................................84
Classes and Casting.....................................................................................................................................................86
Classes and Collections...................................................................................................................................87
Collection Casting...........................................................................................................................................87
Differences Between Apex Classes and Java Classes...................................................................................................88

ii

Table of Contents

Class Definition Creation............................................................................................................................................89


Naming Conventions.......................................................................................................................................90
Name Shadowing............................................................................................................................................90
Namespace Prefix........................................................................................................................................................91
Using the System Namespace..........................................................................................................................91
Namespace, Class, and Variable Name Precedence.........................................................................................92
Type Resolution and System Namespace for Types........................................................................................93
Apex Code Versions....................................................................................................................................................94
Setting the Salesforce API Version for Classes and Triggers..........................................................................94
Setting Package Versions for Apex Classes and Triggers................................................................................95
Lists of Custom Types and Sorting.............................................................................................................................95
Using Custom Types in Map Keys and Sets...............................................................................................................95

Chapter 7: Working with Data in Apex.......................................................................................99


sObject Types............................................................................................................................................................100
Accessing sObject Fields...............................................................................................................................101
Validating sObjects and Fields .....................................................................................................................102
Adding and Retrieving Data.....................................................................................................................................102
DML.........................................................................................................................................................................103
DML Statements vs. Database Class Methods.............................................................................................103
DML Operations As Atomic Transactions...................................................................................................104
How DML Works........................................................................................................................................105
DML Operations..........................................................................................................................................106
DML Exceptions and Error Handling..........................................................................................................116
More About DML........................................................................................................................................117
Locking Records............................................................................................................................................126
SOQL and SOSL Queries........................................................................................................................................127
Working with SOQL and SOSL Query Results...........................................................................................129
Accessing sObject Fields Through Relationships..........................................................................................129
Understanding Foreign Key and Parent-Child Relationship SOQL Queries...............................................131
Working with SOQL Aggregate Functions..................................................................................................131
Working with Very Large SOQL Queries....................................................................................................132
Using SOQL Queries That Return One Record...........................................................................................134
Improving Performance by Not Searching on Null Values...........................................................................134
Working with Polymorphic Relationships in SOQL Queries.......................................................................135
Using Apex Variables in SOQL and SOSL Queries.....................................................................................136
Querying All Records with a SOQL Statement............................................................................................138
SOQL For Loops......................................................................................................................................................138
sObject Collections....................................................................................................................................................140
Lists of sObjects............................................................................................................................................140
Sorting Lists of sObjects................................................................................................................................142
Expanding sObject and List Expressions......................................................................................................144
Sets of Objects...............................................................................................................................................145
Maps of sObjects...........................................................................................................................................145
Dynamic Apex...........................................................................................................................................................147
iii

Table of Contents

Understanding Apex Describe Information...................................................................................................147


Using Field Tokens.......................................................................................................................................149
Understanding Describe Information Permissions........................................................................................151
Describing sObjects Using Schema Method.................................................................................................151
Describing Tabs Using Schema Methods......................................................................................................152
Accessing All sObjects...................................................................................................................................153
Accessing All Data Categories Associated with an sObject..........................................................................153
Dynamic SOQL............................................................................................................................................157
Dynamic SOSL.............................................................................................................................................159
Dynamic DML..............................................................................................................................................159
Apex Security and Sharing........................................................................................................................................162
Enforcing Sharing Rules................................................................................................................................162
Enforcing Object and Field Permissions.......................................................................................................163
Class Security.................................................................................................................................................164
Understanding Apex Managed Sharing.........................................................................................................165
Security Tips for Apex and Visualforce Development...................................................................................176
Custom Settings........................................................................................................................................................183

Ways to Invoke Apex........................................................................................................................185


Chapter 8: Invoking Apex........................................................................................................185
Anonymous Blocks....................................................................................................................................................186
Triggers.....................................................................................................................................................................187
Bulk Triggers.................................................................................................................................................188
Trigger Syntax...............................................................................................................................................188
Trigger Context Variables.............................................................................................................................189
Context Variable Considerations...................................................................................................................191
Common Bulk Trigger Idioms......................................................................................................................192
Defining Triggers..........................................................................................................................................193
Triggers and Merge Statements.....................................................................................................................195
Triggers and Recovered Records...................................................................................................................195
Triggers and Order of Execution...................................................................................................................196
Operations that Don't Invoke Triggers.........................................................................................................197
Entity and Field Considerations in Triggers.................................................................................................199
Trigger Exceptions........................................................................................................................................200
Trigger and Bulk Request Best Practices.......................................................................................................201
Asynchronous Apex...................................................................................................................................................202
Future Methods.............................................................................................................................................202
Future Methods with Higher Limits (Pilot).................................................................................................204
Apex Scheduler..............................................................................................................................................206
Batch Apex....................................................................................................................................................212
Web Services.............................................................................................................................................................224
Exposing Apex Methods as SOAP Web Services.........................................................................................224
Exposing Apex Classes as REST Web Services............................................................................................226
Apex Email Service...................................................................................................................................................235

iv

Table of Contents

Using the InboundEmail Object...................................................................................................................236


Visualforce Classes....................................................................................................................................................237
Invoking Apex Using JavaScript................................................................................................................................238
JavaScript Remoting......................................................................................................................................238
Apex in AJAX...............................................................................................................................................239

Chapter 9: Apex Transactions and Governor Limits..................................................................241


Apex Transactions.....................................................................................................................................................242
Understanding Execution Governors and Limits......................................................................................................243
Using Governor Limit Email Warnings...................................................................................................................249
Running Apex within Governor Execution Limits...................................................................................................249

Chapter 10: Using Salesforce Features with Apex......................................................................252


Working with Chatter in Apex.................................................................................................................................253
Chatter in Apex Quick Start..........................................................................................................................254
Chatter in Apex Examples.............................................................................................................................258
Using ConnectApi Input and Output Classes...............................................................................................262
Accessing ConnectApi Data in Communities and Portals............................................................................262
Working with Feeds and Feed Elements.......................................................................................................263
Understanding Limits for ConnectApi Classes.............................................................................................272
Serializing and Deserializing ConnectApi Obejcts........................................................................................272
ConnectApi Versioning and Equality Checking...........................................................................................272
Casting ConnectApi Objects.........................................................................................................................273
Wildcards.......................................................................................................................................................273
Testing ConnectApi Code............................................................................................................................274
Differences Between ConnectApi Classes and Other Apex Classes..............................................................275
Approval Processing..................................................................................................................................................276
Apex Approval Processing Example..............................................................................................................277
Outbound Email.......................................................................................................................................................277
Inbound Email..........................................................................................................................................................280
Knowledge Management...........................................................................................................................................280
Actions......................................................................................................................................................................280
Force.com Sites.........................................................................................................................................................281
Rewriting URLs for Force.com Sites........................................................................................................................281
Support Classes.........................................................................................................................................................287
Visual Workflow.......................................................................................................................................................288
Passing Data to a Flow Using the Process.Plugin Interface......................................................................................289
Implementing the Process.Plugin Interface...................................................................................................290
Using the Process.PluginRequest Class.........................................................................................................291
Using the Process.PluginResult Class............................................................................................................292
Using the Process.PluginDescribeResult Class..............................................................................................292
Process.Plugin Data Type Conversions.........................................................................................................294
Sample Process.Plugin Implementation for Lead Conversion.......................................................................294
Communities.............................................................................................................................................................300
Zones.........................................................................................................................................................................300

Table of Contents

Analytics API via Apex.............................................................................................................................................301


Requirements and Limitations......................................................................................................................301
Run Reports...................................................................................................................................................302
List Asynchronous Runs of a Report.............................................................................................................303
Get Report Metadata.....................................................................................................................................303
Get Report Data............................................................................................................................................304
Filter Reports.................................................................................................................................................305
Decode the Fact Map....................................................................................................................................306
Test Reports..................................................................................................................................................308

Chapter 11: Integration and Apex Utilities................................................................................311


Invoking Callouts Using Apex..................................................................................................................................312
Adding Remote Site Settings........................................................................................................................312
SOAP Services: Defining a Class from a WSDL Document........................................................................312
Invoking HTTP Callouts..............................................................................................................................323
Using Certificates..........................................................................................................................................331
Callout Limits and Limitations.....................................................................................................................333
JSON Support...........................................................................................................................................................334
Roundtrip Serialization and Deserialization..................................................................................................335
JSON Generator............................................................................................................................................337
JSON Parsing................................................................................................................................................338
XML Support............................................................................................................................................................340
Reading and Writing XML Using Streams...................................................................................................340
Reading and Writing XML Using the DOM...............................................................................................343
Securing Your Data...................................................................................................................................................346
Encoding Your Data.................................................................................................................................................348
Using Patterns and Matchers....................................................................................................................................349
Using Regions................................................................................................................................................350
Using Match Operations...............................................................................................................................351
Using Bounds................................................................................................................................................351
Understanding Capturing Groups.................................................................................................................351
Pattern and Matcher Example.......................................................................................................................352

Finishing Touches............................................................................................................................354
Chapter 12: Debugging Apex...................................................................................................354
Understanding the Debug Log..................................................................................................................................355
Working with Logs in the Developer Console..............................................................................................359
Debugging Apex API Calls...........................................................................................................................371
Exceptions in Apex....................................................................................................................................................372
Exception Statements....................................................................................................................................373
Exception Handling Example.......................................................................................................................374
Built-In Exceptions and Common Methods.................................................................................................376
Catching Different Exception Types.............................................................................................................380
Creating Custom Exceptions.........................................................................................................................381

vi

Table of Contents

Chapter 13: Testing Apex.........................................................................................................384


Understanding Testing in Apex................................................................................................................................385
What to Test in Apex................................................................................................................................................385
What are Apex Unit Tests?.......................................................................................................................................386
Accessing Private Test Class Members.........................................................................................................388
Understanding Test Data..........................................................................................................................................390
Isolation of Test Data from Organization Data in Unit Tests......................................................................390
Using the isTest(SeeAllData=true) Annotation............................................................................................392
Loading Test Data.........................................................................................................................................393
Common Test Utility Classes for Test Data Creation..................................................................................394
Running Unit Test Methods.....................................................................................................................................395
Using the runAs Method...............................................................................................................................398
Using Limits, startTest, and stopTest...........................................................................................................399
Adding SOSL Queries to Unit Tests............................................................................................................400
Testing Best Practices................................................................................................................................................400
Testing Example.......................................................................................................................................................402

Chapter 14: Deploying Apex....................................................................................................407


Using Change Sets To Deploy Apex.........................................................................................................................408
Using the Force.com IDE to Deploy Apex...............................................................................................................408
Using the Force.com Migration Tool........................................................................................................................408
Understanding deploy....................................................................................................................................410
Understanding retrieveCode..........................................................................................................................411
Understanding runTests()..............................................................................................................................413
Using SOAP API to Deploy Apex............................................................................................................................413

Chapter 15: Distributing Apex Using Managed Packages..........................................................414


What is a Package?....................................................................................................................................................415
Package Versions.......................................................................................................................................................415
Deprecating Apex......................................................................................................................................................415
Behavior in Package Versions....................................................................................................................................416
Versioning Apex Code Behavior...................................................................................................................416
Apex Code Items that Are Not Versioned....................................................................................................417
Testing Behavior in Package Versions...........................................................................................................417

Chapter 16: Reference......................................................................................................................420


Apex DML Operations.........................................................................................................................................................421
Apex DML Statements.............................................................................................................................................421
Insert Statement............................................................................................................................................422
Update Statement..........................................................................................................................................422
Upsert Statement...........................................................................................................................................423
Delete Statement...........................................................................................................................................424
Undelete Statement.......................................................................................................................................424
Merge Statement...........................................................................................................................................425
ApexPages Namespace..........................................................................................................................................................425
vii

Table of Contents

Action Class..............................................................................................................................................................426
Action Constructors......................................................................................................................................427
Action Methods.............................................................................................................................................428
Component Class......................................................................................................................................................428
Dynamic Component Properties...................................................................................................................428
IdeaStandardController Class...................................................................................................................................430
IdeaStandardController Methods..................................................................................................................431
IdeaStandardSetController Class..............................................................................................................................432
IdeaStandardSetController Methods.............................................................................................................434
KnowledgeArticleVersionStandardController Class.................................................................................................435
KnowledgeArticleVersionStandardController Constructors.........................................................................437
KnowledgeArticleVersionStandardController Methods................................................................................437
Message Class............................................................................................................................................................438
Message Constructors....................................................................................................................................439
Message Methods..........................................................................................................................................441
StandardController Class..........................................................................................................................................442
StandardController Constructors..................................................................................................................443
StandardController Methods.........................................................................................................................443
StandardSetController Class.....................................................................................................................................447
StandardSetController Constructors.............................................................................................................448
StandardSetController Methods....................................................................................................................449
Approval Namespace.............................................................................................................................................................455
ProcessRequest Class.................................................................................................................................................455
ProcessRequest Methods...............................................................................................................................455
ProcessResult Class...................................................................................................................................................457
ProcessResult Methods..................................................................................................................................457
ProcessSubmitRequest Class.....................................................................................................................................459
ProcessSubmitRequest Methods...................................................................................................................459
ProcessWorkitemRequest Class................................................................................................................................460
ProcessWorkitemRequest Methods..............................................................................................................460
Auth Namespace...................................................................................................................................................................462
AuthToken Class......................................................................................................................................................462
AuthToken Methods.....................................................................................................................................462
RegistrationHandler Interface...................................................................................................................................464
RegistrationHandler Methods.......................................................................................................................464
Storing User Information and Getting Access Tokens..................................................................................466
Auth.RegistrationHandler Example Implementation...................................................................................467
UserData Class..........................................................................................................................................................468
UserData Constructors..................................................................................................................................468
UserData Properties.......................................................................................................................................469
Canvas Namespace................................................................................................................................................................472
ApplicationContext Interface....................................................................................................................................473
ApplicationContext Methods........................................................................................................................473
CanvasLifecycleHandler Interface.............................................................................................................................476

viii

Table of Contents

CanvasLifecycleHandler Methods.................................................................................................................476
ContextTypeEnum Enum.........................................................................................................................................478
EnvironmentContext Interface..................................................................................................................................478
EnvironmentContext Methods.....................................................................................................................479
RenderContext Interface...........................................................................................................................................484
RenderContext Methods...............................................................................................................................484
Test Class..................................................................................................................................................................486
Test Constants...............................................................................................................................................486
Test Methods................................................................................................................................................487
Canvas Exceptions.....................................................................................................................................................489
ChatterAnswers Namespace..................................................................................................................................................490
AccountCreator Interface..........................................................................................................................................490
AccountCreator Methods..............................................................................................................................490
AccountCreator Example Implementation....................................................................................................491
ConnectApi Namespace........................................................................................................................................................492
Announcements Class...............................................................................................................................................493
Announcements Methods.............................................................................................................................494
Chatter Class.............................................................................................................................................................496
Chatter Methods...........................................................................................................................................497
ChatterFavorites Class...............................................................................................................................................500
ChatterFavorites Methods.............................................................................................................................501
ChatterFeeds Class....................................................................................................................................................520
ChatterFeeds Methods..................................................................................................................................520
ChatterGroups Class.................................................................................................................................................724
ChatterGroups Methods...............................................................................................................................724
ChatterMessages Class..............................................................................................................................................756
ChatterMessages Methods............................................................................................................................756
ChatterUsers Class....................................................................................................................................................779
ChatterUsers Methods..................................................................................................................................779
Communities Class...................................................................................................................................................804
Communities Methods..................................................................................................................................804
CommunityModeration Class...................................................................................................................................806
CommunityModeration Methods.................................................................................................................806
Organization Class....................................................................................................................................................817
Organization Methods..................................................................................................................................818
Mentions Class..........................................................................................................................................................818
Mentions Methods........................................................................................................................................818
RecordDetails Class...................................................................................................................................................824
RecordDetails Methods.................................................................................................................................824
Records Class............................................................................................................................................................827
Records Methods...........................................................................................................................................827
Topics Class..............................................................................................................................................................829
Topics Methods.............................................................................................................................................830
UserProfiles Class......................................................................................................................................................857

ix

Table of Contents

UserProfiles Methods....................................................................................................................................857
Zones Class...............................................................................................................................................................857
Zones Methods..............................................................................................................................................858
ConnectApi Input Classes.........................................................................................................................................864
ConnectApi.AnnouncementInput Class.......................................................................................................864
ConnectApi.BinaryInput Class.....................................................................................................................865
ConnectApi.CanvasAttachmentInput Class.................................................................................................865
ConnectApi.ChatterGroupInput Class.........................................................................................................865
ConnectApi.CommentInput Class................................................................................................................866
ConnectApi.ContentAttachmentInput Class................................................................................................866
ConnectApi.FeedElementInput Class...........................................................................................................867
ConnectApi.FeedItemAttachmentInput Class..............................................................................................867
ConnectApi.FeedItemInput Class.................................................................................................................867
ConnectApi.GroupInformationInput Class..................................................................................................868
ConnectApi.HashtagSegmentInput Class.....................................................................................................868
ConnectApi.LinkAttachmentInput Class.....................................................................................................868
ConnectApi.LinkSegmentInput Class..........................................................................................................868
ConnectApi.MentionSegmentInput Class....................................................................................................869
ConnectApi.MessageBodyInput Class..........................................................................................................869
ConnectApi.MessageSegmentInput Class....................................................................................................869
ConnectApi.NewFileAttachmentInput Class...............................................................................................869
ConnectApi.PhotoInput Class......................................................................................................................870
ConnectApi.PollAttachmentInput Class.......................................................................................................870
ConnectApi.TextSegmentInput Class...........................................................................................................870
ConnectApi.TopicInput Class.......................................................................................................................870
ConnectApi.UserInput Class.........................................................................................................................871
ConnectApi Output Classes......................................................................................................................................871
ConnectApi.AbstractBundleCapability Class...............................................................................................871
ConnectApi.AbstractMessageBody Class.....................................................................................................872
ConnectApi.AbstractRecordField Class........................................................................................................872
ConnectApi.AbstractRecordView Class........................................................................................................873
ConnectApi.Actor Class................................................................................................................................873
ConnectApi.ActorWithId Class....................................................................................................................874
ConnectApi.Address Class............................................................................................................................874
ConnectApi.Announcement..........................................................................................................................874
ConnectApi.AnnouncementPage..................................................................................................................875
ConnectApi.ApprovalAttachment Class.......................................................................................................875
ConnectApi.ApprovalPostTemplateField Class............................................................................................876
ConnectApi.BannerCapability Class.............................................................................................................876
ConnectApi.BasicTemplateAttachment Class..............................................................................................876
ConnectApi.BatchResult...............................................................................................................................877
ConnectApi.BlankRecordField Class............................................................................................................879
ConnectApi.BookmarksCapability Class......................................................................................................879
ConnectApi.Bundle Class.............................................................................................................................879

Table of Contents

ConnectApi.CanvasTemplateAttachment Class...........................................................................................880
ConnectApi.CaseComment Class.................................................................................................................880
ConnectApi.ChatterActivity Class................................................................................................................881
ConnectApi.ChatterConversation Class.......................................................................................................881
ConnectApi.ChatterConversationPage Class................................................................................................881
ConnectApi.ChatterConversationSummary Class........................................................................................882
ConnectApi.ChatterGroup Class..................................................................................................................882
ConnectApi.ChatterGroupDetail Class........................................................................................................883
ConnectApi.ChatterGroupPage Class..........................................................................................................884
ConnectApi.ChatterGroupSummary Class...................................................................................................884
ConnectApi.ChatterGroupSummaryPage Class...........................................................................................884
ConnectApi.ChatterLike Class.....................................................................................................................884
ConnectApi.ChatterLikePage Class..............................................................................................................885
ConnectApi.ChatterLikesCapability Class...................................................................................................885
ConnectApi.ChatterMessage Class...............................................................................................................885
ConnectApi.ChatterMessagePage Class.......................................................................................................886
ConnectApi.ClientInfo Class........................................................................................................................886
ConnectApi.Comment Class........................................................................................................................886
ConnectApi.CommentPage Class.................................................................................................................887
ConnectApi.CommentsCapability Class.......................................................................................................888
ConnectApi.Community Class.....................................................................................................................888
ConnectApi.CommunityPage Class..............................................................................................................889
ConnectApi.ComplexSegment Class............................................................................................................889
ConnectApi.CompoundRecordField Class...................................................................................................889
ConnectApi.ContentAttachment Class........................................................................................................889
ConnectApi.CurrencyRecordField Class.......................................................................................................891
ConnectApi.DashboardComponentAttachment Class.................................................................................891
ConnectApi.DateRecordField Class.............................................................................................................891
ConnectApi.EmailAddress Class..................................................................................................................891
ConnectApi.EmailMessage Class..................................................................................................................892
ConnectApi.EntityLinkSegment Class.........................................................................................................892
ConnectApi.Features Class...........................................................................................................................892
ConnectApi.Feed Class.................................................................................................................................894
ConnectApi.FeedBody Class.........................................................................................................................894
ConnectApi.FeedDirectory Class..................................................................................................................894
ConnectApi.FeedDirectoryItem Class..........................................................................................................894
ConnectApi.FeedElement Class...................................................................................................................895
ConnectApi.FeedElementCapabilities Class.................................................................................................897
ConnectApi.FeedElementCapability Class...................................................................................................897
ConnectApi.FeedElementPage Class............................................................................................................898
ConnectApi.FeedFavorite Class....................................................................................................................899
ConnectApi.FeedFavorites Class...................................................................................................................899
ConnectApi.FeedItem Class.........................................................................................................................899
ConnectApi.FeedItemAttachment Class......................................................................................................903

xi

Table of Contents

ConnectApi.FeedItemPage Class..................................................................................................................903
ConnectApi.FeedItemTopicPage Class........................................................................................................904
ConnectApi.FeedModifiedInfo Class...........................................................................................................904
ConnectApi.FeedPoll Class...........................................................................................................................904
ConnectApi.FeedPollChoice Class...............................................................................................................905
ConnectApi.FieldChangeSegment Class......................................................................................................905
ConnectApi.FieldChangeNameSegment Class.............................................................................................905
ConnectApi.FieldChangeValueSegment Class.............................................................................................905
ConnectApi.File Class...................................................................................................................................905
ConnectApi.FileSummary Class...................................................................................................................907
ConnectApi.FollowerPage Class...................................................................................................................908
ConnectApi.FollowingCounts Class.............................................................................................................908
ConnectApi.FollowingPage Class.................................................................................................................908
ConnectApi.GenericBundleCapability Class................................................................................................909
ConnectApi.GlobalInfluence Class...............................................................................................................909
ConnectApi.GroupChatterSettings Class.....................................................................................................909
ConnectApi.GroupInformation Class...........................................................................................................909
ConnectApi.GroupMember Class.................................................................................................................909
ConnectApi.GroupMemberPage Class.........................................................................................................910
ConnectApi.GroupMembershipRequest Class.............................................................................................910
ConnectApi.GroupMembershipRequests Class............................................................................................911
ConnectApi.HashtagSegment Class.............................................................................................................911
ConnectApi.Icon Class..................................................................................................................................912
ConnectApi.LabeledRecordField Class.........................................................................................................912
ConnectApi.LinkAttachment Class..............................................................................................................912
ConnectApi.LinkSegment Class...................................................................................................................913
ConnectApi.MentionCompletion Class........................................................................................................913
ConnectApi.MentionCompletionPage Class................................................................................................913
ConnectApi.MentionSegment Class.............................................................................................................914
ConnectApi.MentionValidation Class..........................................................................................................914
ConnectApi.MentionValidations Class.........................................................................................................915
ConnectApi.MessageBody Class...................................................................................................................915
ConnectApi.MessageSegment Class.............................................................................................................915
ConnectApi.ModerationCapability Class.....................................................................................................916
ConnectApi.ModerationFlags Class.............................................................................................................916
ConnectApi.MoreChangesSegment Class....................................................................................................917
ConnectApi.Motif Class...............................................................................................................................917
ConnectApi.OrganizationSettings Class.......................................................................................................918
ConnectApi.PercentRecordField Class.........................................................................................................918
ConnectApi.PhoneNumber Class.................................................................................................................918
ConnectApi.Photo Class...............................................................................................................................919
ConnectApi.PicklistRecordField Class.........................................................................................................919
ConnectApi.PollCapability Class..................................................................................................................919
ConnectApi.QuestionAndAnswersCapability...............................................................................................920

xii

Table of Contents

ConnectApi.RecordField Class.....................................................................................................................920
ConnectApi.RecordSnapshotAttachment Class............................................................................................920
ConnectApi.RecordSummary Class..............................................................................................................920
ConnectApi.RecordSummaryList Class........................................................................................................920
ConnectApi.RecordView Class.....................................................................................................................920
ConnectApi.RecordViewSection Class.........................................................................................................921
ConnectApi.Reference Class.........................................................................................................................921
ConnectApi.ReferenceRecordField Class.....................................................................................................921
ConnectApi.ReferenceWithDateRecordField Class.....................................................................................922
ConnectApi.ResourceLinkSegment Class.....................................................................................................922
ConnectApi.Subscription Class.....................................................................................................................922
ConnectApi.TextSegment Class...................................................................................................................922
ConnectApi.TimeZone Class........................................................................................................................922
ConnectApi.Topic Class...............................................................................................................................923
ConnectApi.TopicEndorsement Class..........................................................................................................923
ConnectApi.TopicEndorsementCollection Class.........................................................................................923
ConnectApi.TopicPage Class........................................................................................................................924
ConnectApi.TopicsCapability Class..............................................................................................................924
ConnectApi.TopicSuggestion Class..............................................................................................................924
ConnectApi.TopicSuggestionPage Class......................................................................................................924
ConnectApi.TrackedChangeAttachment Class............................................................................................924
ConnectApi.TrackedChangeBundleCapability.............................................................................................924
ConnectApi.TrackedChangeItem Class........................................................................................................925
ConnectApi.UnauthenticatedUser Class.......................................................................................................925
ConnectApi.UnreadConversationCount Class..............................................................................................925
ConnectApi.User Class.................................................................................................................................925
ConnectApi.UserCapabilities Class...............................................................................................................926
ConnectApi.UserChatterSettings Class........................................................................................................927
ConnectApi.UserDetail Class........................................................................................................................927
ConnectApi.UserGroupPage Class...............................................................................................................928
ConnectApi.UserPage Class..........................................................................................................................928
ConnectApi.UserProfile Class.......................................................................................................................929
ConnectApi.UserProfileTab Class................................................................................................................929
ConnectApi.UserSettings Class.....................................................................................................................929
ConnectApi.UserSummary Class..................................................................................................................930
ConnectApi.Zone Class................................................................................................................................930
ConnectApi.ZonePage Class.........................................................................................................................931
ConnectApi.ZoneSearchPage Class..............................................................................................................931
ConnectApi.ZoneSearchResult Class............................................................................................................932
ConnectApi Enums...................................................................................................................................................932
ConnectApi Exceptions............................................................................................................................................940
Database Namespace.............................................................................................................................................................940
Batchable Interface....................................................................................................................................................941
Batchable Methods........................................................................................................................................941

xiii

Table of Contents

BatchableContext Interface.......................................................................................................................................943
BatchableContext Methods...........................................................................................................................943
DeletedRecord Class.................................................................................................................................................944
DeletedRecord Methods................................................................................................................................944
DeleteResult Class.....................................................................................................................................................945
DeleteResult Methods...................................................................................................................................946
DMLOptions Class...................................................................................................................................................947
DmlOptions Properties.................................................................................................................................947
DmlOptions.AssignmentRuleHeader Class..............................................................................................................949
DmlOptions.AssignmentRuleHeader Properties..........................................................................................950
DmlOptions.EmailHeader Class..............................................................................................................................951
DmlOptions.EmailHeader Properties...........................................................................................................951
EmptyRecycleBinResult Class..................................................................................................................................953
EmptyRecycleBinResult Methods.................................................................................................................953
Error Class.................................................................................................................................................................954
Error Methods...............................................................................................................................................954
GetDeletedResult Class............................................................................................................................................955
GetDeletedResult Methods...........................................................................................................................955
GetUpdatedResult Class...........................................................................................................................................956
GetUpdatedResult Methods..........................................................................................................................956
LeadConvert Class....................................................................................................................................................957
LeadConvert Constructors............................................................................................................................958
LeadConvert Methods...................................................................................................................................958
LeadConvertResult Class..........................................................................................................................................964
LeadConvertResult Methods........................................................................................................................965
MergeResult Class.....................................................................................................................................................966
MergeResult Methods...................................................................................................................................967
QueryLocator Class...................................................................................................................................................968
QueryLocator Methods.................................................................................................................................968
QueryLocatorIterator Class.......................................................................................................................................969
QueryLocatorIterator Methods.....................................................................................................................970
SaveResult Class........................................................................................................................................................970
SaveResult Methods......................................................................................................................................971
UndeleteResult Class.................................................................................................................................................972
UndeleteResult Methods...............................................................................................................................972
UpsertResult Class....................................................................................................................................................973
UpsertResult Methods...................................................................................................................................974
Dom Namespace...................................................................................................................................................................975
Document Class........................................................................................................................................................975
Document Constructors................................................................................................................................975
Document Methods.......................................................................................................................................976
XmlNode Class.........................................................................................................................................................977
XmlNode Methods........................................................................................................................................978
Flow Namespace...................................................................................................................................................................987

xiv

Table of Contents

Interview Class..........................................................................................................................................................987
Interview Methods.........................................................................................................................................988
KbManagement Namespace.................................................................................................................................................989
PublishingService Class.............................................................................................................................................989
PublishingService Methods...........................................................................................................................990
Messaging Namespace........................................................................................................................................................1000
Email Class (Base Email Methods).........................................................................................................................1001
Email Methods............................................................................................................................................1001
EmailFileAttachment Class....................................................................................................................................1004
EmailFileAttachment Constructors.............................................................................................................1004
EmailFileAttachment Methods...................................................................................................................1004
InboundEmail Class................................................................................................................................................1006
InboundEmail Constructors........................................................................................................................1006
InboundEmail Properties............................................................................................................................1006
InboundEmail.BinaryAttachment Class.................................................................................................................1011
InboundEmail.BinaryAttachment Constructors.........................................................................................1011
InboundEmail.BinaryAttachment Properties..............................................................................................1012
InboundEmail.TextAttachment Class....................................................................................................................1012
InboundEmail.TextAttachment Constructors.............................................................................................1013
InboundEmail.TextAttachment Properties.................................................................................................1013
InboundEmailResult Class......................................................................................................................................1015
InboundEmailResult Properties..................................................................................................................1015
InboundEnvelope Class...........................................................................................................................................1015
InboundEnvelope Properties.......................................................................................................................1016
MassEmailMessage Class........................................................................................................................................1016
MassEmailMessage Constructors................................................................................................................1017
MassEmailMessage Methods......................................................................................................................1017
InboundEmail.Header Class...................................................................................................................................1019
InboundEmail.Header Properties................................................................................................................1019
PushNotification Class............................................................................................................................................1020
PushNotification Constructors....................................................................................................................1020
PushNotification Methods..........................................................................................................................1021
PushNotificationPayload Class................................................................................................................................1022
PushNotificationPayload Methods..............................................................................................................1023
SendEmailError Class.............................................................................................................................................1025
SendEmailError Methods...........................................................................................................................1025
SendEmailResult Class............................................................................................................................................1026
SendEmailResult Methods..........................................................................................................................1027
SingleEmailMessage Methods................................................................................................................................1027
SingleEmailMessage Constructors..............................................................................................................1028
SingleEmailMessage Methods....................................................................................................................1028
Process Namespace..............................................................................................................................................................1035
Plugin Interface.......................................................................................................................................................1035
Plugin Methods...........................................................................................................................................1035

xv

Table of Contents

Plugin Example Implementation.................................................................................................................1036


PluginDescribeResult Class.....................................................................................................................................1037
PluginDescribeResult Constructors.............................................................................................................1037
PluginDescribeResult Properties.................................................................................................................1038
PluginDescribeResult.InputParameter Class...........................................................................................................1039
PluginDescribeResult.InputParameter Constructors...................................................................................1039
PluginDescribeResult.InputParameter Properties.......................................................................................1041
PluginDescribeResult.OutputParameter Class........................................................................................................1042
PluginDescribeResult.OutputParameter Constructors................................................................................1042
PluginDescribeResult.OutputParameter Properties....................................................................................1043
PluginRequest Class................................................................................................................................................1044
PluginRequest Properties.............................................................................................................................1045
PluginResult Class...................................................................................................................................................1045
PluginResult Properties...............................................................................................................................1045
QuickAction Namespace.....................................................................................................................................................1045
DescribeAvailableQuickActionResult Class............................................................................................................1046
DescribeAvailableQuickActionResult Methods..........................................................................................1046
DescribeLayoutComponent Class...........................................................................................................................1047
DescribeLayoutComponent Methods.........................................................................................................1048
DescribeLayoutItem Class.......................................................................................................................................1049
DescribeLayoutItem Methods.....................................................................................................................1049
DescribeLayoutRow Class.......................................................................................................................................1051
DescribeLayoutRow Methods.....................................................................................................................1051
DescribeLayoutSection Class..................................................................................................................................1052
DescribeLayoutSection Methods.................................................................................................................1052
DescribeQuickActionDefaultValue Class...............................................................................................................1053
DescribeQuickActionDefaultValue Methods..............................................................................................1054
DescribeQuickActionResult Class..........................................................................................................................1054
DescribeQuickActionResult Methods.........................................................................................................1055
QuickActionRequest Class......................................................................................................................................1059
QuickActionRequest Constructors..............................................................................................................1060
QuickActionRequest Methods....................................................................................................................1060
QuickActionResult Class........................................................................................................................................1062
QuickActionResult Methods.......................................................................................................................1063
Reports Namespace.............................................................................................................................................................1064
AggregateColumn Class..........................................................................................................................................1066
AggregateColumn Methods........................................................................................................................1066
ColumnDataType Enum.........................................................................................................................................1067
ColumnSortOrder Enum........................................................................................................................................1068
DateGranularity Enum...........................................................................................................................................1068
DetailColumn Class................................................................................................................................................1069
DetailColumn Instance Methods................................................................................................................1069
Dimension Class......................................................................................................................................................1070
Dimension Methods....................................................................................................................................1070

xvi

Table of Contents

FilterOperator Class................................................................................................................................................1071
FilterOperator Methods..............................................................................................................................1071
FilterValue Class.....................................................................................................................................................1072
FilterValue Methods....................................................................................................................................1072
GroupingColumn Class..........................................................................................................................................1072
GroupingColumn Methods.........................................................................................................................1073
GroupingInfo Class.................................................................................................................................................1074
GroupingInfo Methods...............................................................................................................................1074
GroupingValue Class...............................................................................................................................................1075
GroupingValue Methods.............................................................................................................................1075
ReportCurrency Class..............................................................................................................................................1077
ReportCurrency Methods............................................................................................................................1077
ReportDataCell Class..............................................................................................................................................1078
ReportDataCell Methods............................................................................................................................1078
ReportDescribeResult Class....................................................................................................................................1079
ReportDescribeResult Methods..................................................................................................................1079
ReportDetailRow Class...........................................................................................................................................1080
ReportDetailRow Methods.........................................................................................................................1080
ReportExtendedMetadata Class..............................................................................................................................1080
ReportExtendedMetadata Methods............................................................................................................1080
ReportFact Class.....................................................................................................................................................1081
ReportFact Methods....................................................................................................................................1082
ReportFactWithDetails Class..................................................................................................................................1082
ReportFactWithDetails Methods................................................................................................................1082
ReportFilter Class....................................................................................................................................................1083
ReportFilter Constructors............................................................................................................................1084
ReportFilter Methods..................................................................................................................................1084
ReportFormat Enum...............................................................................................................................................1086
ReportInstance Class...............................................................................................................................................1087
ReportInstance Methods.............................................................................................................................1087
ReportManager Class..............................................................................................................................................1089
ReportManager Methods............................................................................................................................1089
ReportMetadata Class.............................................................................................................................................1094
ReportMetadata Methods...........................................................................................................................1094
ReportResults Class.................................................................................................................................................1100
ReportResults Methods...............................................................................................................................1100
ReportType Class....................................................................................................................................................1102
ReportType Methods..................................................................................................................................1102
ReportTypeColumn Class.......................................................................................................................................1103
ReportTypeColumn Methods.....................................................................................................................1103
ReportTypeColumnCategory Class........................................................................................................................1104
ReportTypeColumnCategory Methods.......................................................................................................1105
ReportTypeMetadata Class.....................................................................................................................................1105
ReportTypeMetadata Methods...................................................................................................................1105

xvii

Table of Contents

SummaryValue Class...............................................................................................................................................1106
SummaryValue Methods.............................................................................................................................1106
Reports Exceptions..................................................................................................................................................1107
Schema Namespace.............................................................................................................................................................1107
ChildRelationship Class..........................................................................................................................................1108
ChildRelationship Methods........................................................................................................................1109
DataCategory Class.................................................................................................................................................1110
DataCategory Methods...............................................................................................................................1111
DataCategoryGroupSobjectTypePair Class............................................................................................................1111
DataCategoryGroupSobjectTypePair Constructors....................................................................................1112
DataCategoryGroupSobjectTypePair Methods..........................................................................................1112
DescribeColorResult Class......................................................................................................................................1113
DescribeColorResult Methods....................................................................................................................1114
DescribeDataCategoryGroupResult Class..............................................................................................................1115
DescribeDataCategoryGroupResult Methods.............................................................................................1116
DescribeDataCategoryGroupStructureResult Class................................................................................................1117
DescribeDataCategoryGroupStructureResult Methods..............................................................................1118
DescribeFieldResult Class.......................................................................................................................................1119
DescribeFieldResult Methods.....................................................................................................................1119
DescribeIconResult Class........................................................................................................................................1133
DescribeIconResult Methods......................................................................................................................1133
DescribeSObjectResult Class..................................................................................................................................1135
DescribeSObjectResult Methods.................................................................................................................1135
DescribeTabResult Class.........................................................................................................................................1143
DescribeTabResult Methods.......................................................................................................................1143
DescribeTabSetResult Class....................................................................................................................................1145
DescribeTabSetResult Methods..................................................................................................................1146
DisplayType Enum.................................................................................................................................................1148
FieldSet Class..........................................................................................................................................................1149
FieldSet Methods........................................................................................................................................1150
FieldSetMember Class............................................................................................................................................1152
FieldSetMember Methods...........................................................................................................................1153
PicklistEntry Class..................................................................................................................................................1154
PicklistEntry Methods.................................................................................................................................1155
RecordTypeInfo Class.............................................................................................................................................1156
RecordTypeInfo Methods...........................................................................................................................1156
SOAPType Enum...................................................................................................................................................1158
SObjectField Class..................................................................................................................................................1158
sObjectField Methods.................................................................................................................................1158
SObjectType Class..................................................................................................................................................1159
SObjectType Methods................................................................................................................................1159
Site Namespace...................................................................................................................................................................1161
UrlRewriter Interface...............................................................................................................................................1162
UrlRewriter Methods..................................................................................................................................1162

xviii

Table of Contents

Support Namespace.............................................................................................................................................................1163
EmailTemplateSelector Interface............................................................................................................................1163
EmailTemplateSelector Methods................................................................................................................1164
EmailTemplateSelector Example Implementation......................................................................................1164
MilestoneTriggerTimeCalculator Interface.............................................................................................................1165
MilestoneTriggerTimeCalculator Methods................................................................................................1166
MilestoneTriggerTimeCalculator Example Implementation......................................................................1166
System Namespace..............................................................................................................................................................1167
Answers Class..........................................................................................................................................................1171
Answers Methods........................................................................................................................................1172
ApexPages Class......................................................................................................................................................1173
ApexPages Methods....................................................................................................................................1173
Approval Class.........................................................................................................................................................1176
Approval Methods.......................................................................................................................................1176
Blob Class................................................................................................................................................................1178
Blob Methods..............................................................................................................................................1178
Boolean Class..........................................................................................................................................................1180
Boolean Methods.........................................................................................................................................1180
BusinessHours Class................................................................................................................................................1181
BusinessHours Methods..............................................................................................................................1181
Cases Class..............................................................................................................................................................1184
Cases Methods............................................................................................................................................1184
Comparable Interface..............................................................................................................................................1185
Comparable Methods..................................................................................................................................1186
Comparable Example Implementation........................................................................................................1186
Cookie Class............................................................................................................................................................1187
Cookie Constructors....................................................................................................................................1189
Cookie Methods..........................................................................................................................................1189
Crypto Class............................................................................................................................................................1191
Crypto Methods..........................................................................................................................................1192
Custom Settings Methods.......................................................................................................................................1200
List Custom Setting Methods.....................................................................................................................1205
Hierarchy Custom Setting Methods...........................................................................................................1207
Database Class.........................................................................................................................................................1210
Database Methods.......................................................................................................................................1211
Date Class...............................................................................................................................................................1237
Date Methods..............................................................................................................................................1237
Datetime Methods..................................................................................................................................................1246
Datetime Methods.......................................................................................................................................1246
Decimal Class..........................................................................................................................................................1264
Rounding Mode..........................................................................................................................................1265
Decimal Methods........................................................................................................................................1266
Double Class...........................................................................................................................................................1274
Double Methods..........................................................................................................................................1275

xix

Table of Contents

EncodingUtil Class.................................................................................................................................................1277
EncodingUtil Methods................................................................................................................................1278
Enum Methods.......................................................................................................................................................1281
Exception Class and Built-In Exceptions................................................................................................................1281
Http Class...............................................................................................................................................................1284
Http Methods..............................................................................................................................................1284
HttpCalloutMock Interface.....................................................................................................................................1285
HttpCalloutMock Methods........................................................................................................................1285
HttpRequest Class...................................................................................................................................................1286
HttpRequest Constructors...........................................................................................................................1287
HttpRequest Methods.................................................................................................................................1287
HttpResponse Class................................................................................................................................................1294
HttpResponse Methods...............................................................................................................................1295
Id Class....................................................................................................................................................................1300
Id Methods..................................................................................................................................................1301
Ideas Class...............................................................................................................................................................1304
Ideas Methods.............................................................................................................................................1307
InstallHandler Interface...........................................................................................................................................1309
InstallHandler Methods..............................................................................................................................1310
InstallHandler Example Implementation....................................................................................................1310
Integer Class............................................................................................................................................................1312
Integer Methods..........................................................................................................................................1312
JSON Class.............................................................................................................................................................1313
JSON Methods............................................................................................................................................1314
JSONGenerator Class.............................................................................................................................................1318
JSONGenerator Methods...........................................................................................................................1319
JSONParser Class....................................................................................................................................................1331
JSONParser Methods..................................................................................................................................1331
JSONToken Enum.................................................................................................................................................1342
Limits Class.............................................................................................................................................................1342
Limits Methods...........................................................................................................................................1343
List Class.................................................................................................................................................................1357
List Constructors.........................................................................................................................................1357
List Methods...............................................................................................................................................1359
Long Class...............................................................................................................................................................1369
Long Methods.............................................................................................................................................1370
Map Class................................................................................................................................................................1371
Map Constructors........................................................................................................................................1371
Map Methods..............................................................................................................................................1373
Matcher Class..........................................................................................................................................................1381
Matcher Methods........................................................................................................................................1382
Math Class..............................................................................................................................................................1393
Math Methods.............................................................................................................................................1393
Messaging Class......................................................................................................................................................1416

xx

Table of Contents

Messaging Methods.....................................................................................................................................1416
MultiStaticResourceCalloutMock Class.................................................................................................................1419
MultiStaticResourceCalloutMock Constructors.........................................................................................1419
MultiStaticResourceCalloutMock Methods................................................................................................1419
Network Class.........................................................................................................................................................1421
Network Constructors.................................................................................................................................1421
Network Methods........................................................................................................................................1422
PageReference Class................................................................................................................................................1423
PageReference Constructors........................................................................................................................1426
PageReference Methods..............................................................................................................................1427
Pattern Class............................................................................................................................................................1432
Pattern Methods..........................................................................................................................................1432
QuickAction Class...................................................................................................................................................1435
QuickAction Methods.................................................................................................................................1436
ResetPasswordResult Class.....................................................................................................................................1439
ResetPasswordResult Methods....................................................................................................................1439
RestContext Class...................................................................................................................................................1440
RestContext Properties................................................................................................................................1440
RestRequest Class...................................................................................................................................................1441
RestRequest Constructors...........................................................................................................................1442
RestRequest Properties................................................................................................................................1442
RestRequest Methods..................................................................................................................................1445
RestResponse Class.................................................................................................................................................1446
RestResponse Constructors.........................................................................................................................1446
RestResponse Properties..............................................................................................................................1447
RestResponse Methods...............................................................................................................................1448
Schedulable Interface...............................................................................................................................................1449
Schedulable Methods...................................................................................................................................1450
SchedulableContext Interface..................................................................................................................................1450
SchedulableContext Methods......................................................................................................................1450
Schema Class...........................................................................................................................................................1451
Schema Methods.........................................................................................................................................1451
Search Class.............................................................................................................................................................1455
Search Methods...........................................................................................................................................1455
SelectOption Class..................................................................................................................................................1455
SelectOption Constructors..........................................................................................................................1457
SelectOption Methods.................................................................................................................................1458
Set Class..................................................................................................................................................................1461
Set Constructors..........................................................................................................................................1461
Set Methods................................................................................................................................................1463
Site Class.................................................................................................................................................................1471
Site Methods...............................................................................................................................................1473
sObject Class...........................................................................................................................................................1486
SObject Methods.........................................................................................................................................1486

xxi

Table of Contents

StaticResourceCalloutMock Class...........................................................................................................................1497
StaticResourceCalloutMock Constructors...................................................................................................1497
StaticResourceCalloutMock Methods.........................................................................................................1498
String Class.............................................................................................................................................................1499
String Methods............................................................................................................................................1499
System Class............................................................................................................................................................1561
System Methods..........................................................................................................................................1561
Test Class................................................................................................................................................................1579
Test Methods..............................................................................................................................................1579
Time Class...............................................................................................................................................................1587
Time Methods.............................................................................................................................................1587
TimeZone Class......................................................................................................................................................1590
TimeZone Methods....................................................................................................................................1591
Type Class...............................................................................................................................................................1593
Type Methods.............................................................................................................................................1594
UninstallHandler Interface......................................................................................................................................1598
UninstallHandler Methods..........................................................................................................................1599
UninstallHandler Example Implementation................................................................................................1600
URL Class...............................................................................................................................................................1601
URL Constructors.......................................................................................................................................1602
URL Methods.............................................................................................................................................1604
UserInfo Class.........................................................................................................................................................1609
UserInfo Methods.......................................................................................................................................1609
Version Class...........................................................................................................................................................1616
Version Constructors...................................................................................................................................1616
Version Methods.........................................................................................................................................1617
WebServiceMock Interface.....................................................................................................................................1619
WebServiceMock Methods.........................................................................................................................1619
XmlStreamReader Class..........................................................................................................................................1620
XmlStreamReader Constructors..................................................................................................................1621
XmlStreamReader Methods........................................................................................................................1621
XmlStreamWriter Class..........................................................................................................................................1633
XmlStreamWriter Constructors..................................................................................................................1633
XmlStreamWriter Methods.........................................................................................................................1633

Appendices.....................................................................................................................................1640
Appendix A: SOAP API and SOAP Headers for Apex.............................................................1640
ApexTestQueueItem...............................................................................................................................................1641
ApexTestResult.......................................................................................................................................................1642
compileAndTest()...................................................................................................................................................1645
CompileAndTestRequest............................................................................................................................1646
CompileAndTestResult...............................................................................................................................1647
compileClasses()......................................................................................................................................................1649
compileTriggers()....................................................................................................................................................1650

xxii

Table of Contents

executeanonymous()................................................................................................................................................1650
ExecuteAnonymousResult...........................................................................................................................1651
runTests()................................................................................................................................................................1651
RunTestsRequest.........................................................................................................................................1653
RunTestsResult...........................................................................................................................................1653
DebuggingHeader...................................................................................................................................................1656
PackageVersionHeader............................................................................................................................................1657

Appendix B: Shipping Invoice Example..................................................................................1659


Shipping Invoice Example Walk-Through.............................................................................................................1659
Shipping Invoice Example Code.............................................................................................................................1661

Appendix C: Reserved Keywords............................................................................................1669


Appendix D: Documentation Typographical Conventions......................................................1671
Glossary.........................................................................................................................................1673
Index..............................................................................................................................................1690

xxiii

GETTING STARTED

Chapter 1
Introduction
In this chapter ...

Introducing Apex
What is Apex?
When Should I Use Apex?
How Does Apex Work?
Developing Code in the Cloud
What's New?
Understanding Apex Core Concepts

In this chapter, youll learn about the Apex programming language, how it
works, and when to use it.

Introduction

Introducing Apex

Introducing Apex
Salesforce.com has changed the way organizations do business by moving enterprise applications that were traditionally
client-server-based into an on-demand, multitenant Web environment, the Force.com platform. This environment allows
organizations to run and customize applications, such as Salesforce Automation and Service & Support, and build new custom
applications based on particular business needs.
While many customization options are available through the Salesforce user interface, such as the ability to define new fields,
objects, workflow, and approval processes, developers can also use the SOAP API to issue data manipulation commands such
as delete(), update() or upsert(), from client-side programs.
These client-side programs, typically written in Java, JavaScript, .NET, or other programming languages grant organizations
more flexibility in their customizations. However, because the controlling logic for these client-side programs is not located
on Force.com platform servers, they are restricted by:

The performance costs of making multiple round-trips to the salesforce.com site to accomplish common business transactions
The cost and complexity of hosting server code, such as Java or .NET, in a secure and robust environment

To address these issues, and to revolutionize the way that developers create on-demand applications, salesforce.com introduces
Force.com Apex code, the first multitenant, on-demand programming language for developers interested in building the next
generation of business applications.

What is Apex?more about when to use Apex, the development process, and some limitations
What's new in this Apex release?
Apex Quick Startdelve straight into the code and write your first Apex class and trigger

What is Apex?
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java
and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button
clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on
objects.

Introduction

What is Apex?

Figure 1: You can add Apex to most system events.


As a language, Apex is:
Integrated
Apex provides built-in support for common Force.com platform idioms, including:
Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in
DmlException handling
Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that
return lists of sObject records
Looping that allows for bulk processing of multiple records at a time
Locking syntax that prevents record update conflicts
Custom public Force.com API calls that can be built from stored Apex methods
Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex
Easy to use
Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax,
loop syntax, object and array notation, and so on. Where Apex introduces new elements, it uses syntax and semantics
that are easy to understand and encourage efficient use of the Force.com platform. Consequently, Apex produces code
that is both succinct and easy to write.

Introduction

When Should I Use Apex?

Data focused
Apex is designed to thread together multiple query and DML statements into a single unit of work on the Force.com
platform server, much as developers use database stored procedures to thread together multiple transaction statements
on a database server. Note that like other database stored procedures, Apex does not attempt to provide general support
for rendering elements in the user interface.
Rigorous
Apex is a strongly-typed language that uses direct references to schema objects such as object and field names. It fails
quickly at compile time if any references are invalid, and stores all custom field, object, and class dependencies in metadata
to ensure they are not deleted while required by active Apex code.
Hosted
Apex is interpreted, executed, and controlled entirely by the Force.com platform.
Multitenant aware
Like the rest of the Force.com platform, Apex runs in a multitenant environment. Consequently, the Apex runtime
engine is designed to guard closely against runaway code, preventing them from monopolizing shared resources. Any
code that violate these limits fail with easy-to-understand error messages.
Automatically upgradeable
Apex never needs to be rewritten when other parts of the Force.com platform are upgraded. Because the compiled code
is stored as metadata in the platform, it always gets automatically upgraded with the rest of the system.
Easy to test
Apex provides built-in support for unit test creation and execution, including test results that indicate how much code
is covered, and which parts of your code could be more efficient. Salesforce.com ensures that Apex code always work as
expected by executing all unit tests stored in metadata prior to any platform upgrades.
Versioned
You can save your Apex code against different versions of the Force.com API. This enables you to maintain behavior.
Apex is included in Performance Edition, Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com.

When Should I Use Apex?


The Salesforce prebuilt applications provide powerful CRM functionality. In addition, Salesforce provides the ability to
customize the prebuilt applications to fit your organization. However, your organization may have complex business processes
that are unsupported by the existing functionality. When this is the case, the Force.com platform includes a number of ways
for advanced administrators and developers to implement custom functionality. These include Apex, Visualforce, and the
SOAP API.

Apex
Use Apex if you want to:

Create Web services.


Create email services.
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object).

Introduction

How Does Apex Work?

Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed,
regardless of whether it originates in the user interface, a Visualforce page, or from SOAP API.

Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and
customizing the Salesforce user interface. With Visualforce you can:

Build wizards and other multistep processes.


Create your own custom flow control through an application.
Define navigation patterns and data-specific rules for optimal, efficient application interaction.

For more information, see the Visualforce Developer's Guide.

SOAP API
Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of
record at a time and does not require any transactional control (such as setting a Savepoint or rolling back changes).
For more information, see the SOAP API Developer's Guide.

How Does Apex Work?


All Apex runs entirely on-demand on the Force.com platform, as shown in the following architecture diagram:

Figure 2: Apex is compiled, stored, and run entirely on the Force.com platform.
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an
abstract set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as
metadata.
When an end-user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform
application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before
returning the result. The end-user observes no differences in execution time from standard platform requests.

Introduction

Developing Code in the Cloud

Developing Code in the Cloud


The Apex programming language is saved and runs in the cloudthe Force.com multitenant platform. Apex is tailored for
data access and data manipulation on the platform, and it enables you to add custom business logic to system events. While
it provides many benefits for automating business processes on the platform, it is not a general purpose programming language.
As such, Apex cannot be used to:

Render elements in the user interface other than error messages


Change standard functionalityApex can only prevent the functionality from happening, or add additional functionality
Create temporary files
Spawn threads
Tip:
All Apex code runs on the Force.com platform, which is a shared resource used by all other organizations. To guarantee
consistent performance and scalability, the execution of Apex is bound by governor limits that ensure no single Apex
execution impacts the overall service of Salesforce. This means all Apex code is limited by the number of operations
(such as DML or SOQL) that it can perform within one process.
All Apex requests return a collection that contains from 1 to 50,000 records. You cannot assume that your code only
works on a single record at a time. Therefore, you must implement programming patterns that take bulk processing
into account. If you dont, you may run into the governor limits.

See Also:
Trigger and Bulk Request Best Practices

What's New?
Review the Summer 14 Release Notes to learn about new and changed Apex features in Summer 14.

Past Releases
For information about new features introduced in previous releases, see:

Spring 14 Release Notes


Winter 14 Release Notes
Summer 13 Release Notes
Spring 13 Release Notes
Winter 13 Release Notes
Summer 12 Release Notes
Spring 12 Release Notes
Winter 12 Release Notes
Summer 11 Release Notes
Spring 11 Release Notes
Winter 11 Release Notes
Summer 10 Release Notes
Spring 10 Release Notes
Winter 10 Release Notes
Summer 09 Release Notes
6

Introduction

Understanding Apex Core Concepts

Spring 09 Release Notes


Winter 09 Release Notes
Summer 08 Release Notes
Spring 08 Release Notes
Winter 08 Release Notes
Summer 07 Release Notes
Spring 07 Release Notes

Understanding Apex Core Concepts


Apex code typically contains many things that you might be familiar with from other programming languages:

Figure 3: Programming elements in Apex


The section describes the basic functionality of Apex, as well as some of the core concepts.

Using Version Settings


In the Salesforce user interface you can specify a version of the Salesforce.com API against which to save your Apex class or
trigger. This setting indicates not only the version of SOAP API to use, but which version of Apex as well. You can change
the version after saving. Every class or trigger name must be unique. You cannot save the same class or trigger against different
versions.
You can also use version settings to associate a class or trigger with a particular version of a managed package that is installed
in your organization from AppExchange. This version of the managed package will continue to be used by the class or trigger
if later versions of the managed package are installed, unless you manually update the version setting. To add an installed
managed package to the settings list, select a package from the list of available packages. The list is only displayed if you have
an installed managed package that is not already associated with the class or trigger.

Introduction

Understanding Apex Core Concepts

For more information about using version settings with managed packages, see About Package Versions in the Salesforce
online help.

Naming Variables, Methods and Classes


You cannot use any of the Apex reserved keywords when naming variables, methods or classes. These include words that are
part of Apex and the Force.com platform, such as list, test, or account, as well as reserved keywords.

Using Variables and Expressions


Apex is a strongly-typed language, that is, you must declare the data type of a variable when you first refer to it. Apex data types
include basic types such as Integer, Date, and Boolean, as well as more advanced types such as lists, maps, objects and sObjects.
Variables are declared with a name and a data type. You can assign a value to a variable when you declare it. You can also
assign values later. Use the following syntax when declaring variables:
datatype variable_name [ = value];

Tip: Note that the semi-colon at the end of the above is not optional. You must end all statements with a semi-colon.

The following are examples of variable declarations:


// The following variable has the data type of Integer with the name Count,
// and has the value of 0.
Integer Count = 0;
// The following variable has the data type of Decimal with the name Total. Note
// that no value has been assigned to it.
Decimal Total;
// The following variable is an account, which is also referred to as an sObject.
Account MyAcct = new Account();

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.

Using Statements
A statement is any coded instruction that performs an action.
In Apex, statements must end with a semicolon and can be one of the following types:

Assignment, such as assigning a value to a variable

Introduction

Understanding Apex Core Concepts

Conditional (if-else)
Loops:
Do-while
While
For

Locking
Data Manipulation Language (DML)
Transaction Control
Method Invoking
Exception Handling

A block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement
would be allowed. For example:
if (true) {
System.debug(1);
System.debug(2);
} else {
System.debug(3);
System.debug(4);
}

In cases where a block consists of only one statement, the curly braces can be left off. For example:
if (true)
System.debug(1);
else
System.debug(2);

Using Collections
Apex has the following types of collections:

Lists (arrays)
Maps
Sets

A list is a collection of elements, such as Integers, Strings, objects, or other collections. Use a list when the sequence of elements
is important. You can have duplicate elements in a list.
The first index position in a list is always 0.
To create a list:

Use the new keyword


Use the List keyword followed by the element type contained within <> characters.

Use the following syntax for creating a list:


List <datatype> list_name
[= new List<datatype>();] |
[=new List<datatype>{value [, value2. . .]};] |
;

Introduction

Understanding Apex Core Concepts

The following example creates a list of Integer, and assigns it to the variable My_List. Remember, because Apex is strongly
typed, you must declare the data type of My_List as a list of Integer.
List<Integer> My_List = new List<Integer>();

For more information, see Lists on page 29.


A set is a collection of unique, unordered elements. It can contain primitive data types, such as String, Integer, Date, and so
on. It can also contain more complex data types, such as sObjects.
To create a set:

Use the new keyword


Use the Set keyword followed by the primitive data type contained within <> characters

Use the following syntax for creating a set:


Set<datatype> set_name
[= new Set<datatype>();] |
[= new Set<datatype>{value [, value2. . .] };] |
;

The following example creates a set of String. The values for the set are passed in using the curly braces {}.
Set<String> My_String = new Set<String>{'a', 'b', 'c'};

For more information, see Sets on page 32.


A map is a collection of key-value pairs. Keys can be any primitive data type. Values can include primitive data types, as well
as objects and other collections. Use a map when finding something by key matters. You can have duplicate values in a map,
but each key must be unique.
To create a map:

Use the new keyword


Use the Map keyword followed by a key-value pair, delimited by a comma and enclosed in <> characters.

Use the following syntax for creating a map:


Map<key_datatype, value_datatype> map_name
[=new map<key_datatype, value_datatype>();] |
[=new map<key_datatype, value_datatype>
{key1_value => value1_value
[, key2_value => value2_value. . .]};] |
;

The following example creates a map that has a data type of Integer for the key and String for the value. In this example, the
values for the map are being passed in between the curly braces {} as the map is being created.
Map<Integer, String> My_Map = new Map<Integer, String>{1 => 'a', 2 => 'b', 3 => 'c'};

For more information, see Maps on page 32.

10

Introduction

Understanding Apex Core Concepts

Using Branching
An if statement is a true-false test that enables your application to do different things based on a condition. The basic syntax
is as follows:
if (Condition){
// Do this if the condition is true
} else {
// Do this if the condition is not true
}

For more information, see Conditional (If-Else) Statements on page 49.

Using Loops
While the if statement enables your application to do things based on a condition, loops tell your application to do the same
thing again and again based on a condition. Apex supports the following types of loops:

Do-while
While
For

A Do-while loop checks the condition after the code has executed.
A While loop checks the condition at the start, before the code executes.
A For loop enables you to more finely control the condition used with the loop. In addition, Apex supports traditional For
loops where you set the conditions, as well as For loops that use lists and SOQL queries as part of the condition.
For more information, see Loops on page 49.

11

Chapter 2
Apex Development Process
In this chapter ...

What is the Apex Development


Process?
Using a Developer or Sandbox
Organization
Learning Apex
Writing Apex Using Development
Environments
Writing Tests
Deploying Apex to a Sandbox
Organization
Deploying Apex to a Salesforce
Production Organization
Adding Apex Code to a Force.com
AppExchange App

In this chapter, youll learn about the Apex development lifecycle, and which
organization and tools to use to develop Apex. Youll also learn about testing
and deploying Apex code.

12

Apex Development Process

What is the Apex Development Process?

What is the Apex Development Process?


We recommend the following process for developing Apex:
1.
2.
3.
4.
5.
6.

Obtain a Developer Edition account.


Learn more about Apex.
Write your Apex.
While writing Apex, you should also be writing tests.
Optionally deploy your Apex to a sandbox organization and do final unit tests.
Deploy your Apex to your Salesforce production organization.

In addition to deploying your Apex, once it is written and tested, you can also add your classes and triggers to a Force.com
AppExchange App package.

Using a Developer or Sandbox Organization


There are three types of organizations where you can run your Apex:

A developer organization: an organization created with a Developer Edition account.


A production organization: an organization that has live users accessing your data.
A sandbox organization: an organization created on your production organization that is a copy of your production
organization.
Note: Apex triggers are available in the Trial Edition of Salesforce; however, they are disabled when you convert to
any other edition. If your newly-signed-up organization includes Apex, you must deploy your code to your organization
using one of the deployment methods.

You can't develop Apex in your Salesforce production organization. Live users accessing the system while you're developing
can destabilize your data or corrupt your application. Instead, you must do all your development work in either a sandbox or
a Developer Edition organization.
If you aren't already a member of the developer community, go to http://developer.salesforce.com/signup and
follow the instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free
Developer Edition organization. Even if you already have an Enterprise, Unlimited, or Performance Edition organization and
a sandbox for creating Apex, we strongly recommends that you take advantage of the resources available in the developer
community.
Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.

Creating a Sandbox Organization


To create or refresh a sandbox organization:
1. From Setup, click Sandboxes or Data Management > Sandboxes.
2. Click New Sandbox.
3. Enter a name and description for the sandbox. You can only change the name when you create or refresh a sandbox.
Tip: We recommend that you choose a name that:

Reflects the purpose of this sandbox, such as QA.

13

Apex Development Process

Learning Apex

Has few characters because Salesforce automatically appends the sandbox name to usernames on user records
in the sandbox environment. Names with fewer characters make sandbox logins easier to type.

4. Select the type of sandbox environment you want.


Note: If you dont see a sandbox option or need licenses for more sandboxes, contact salesforce.com to order
sandboxes for your organization.
If you have reduced the number of sandboxes you purchased, but you still have more sandboxes of a specific type
than allowed, you will be required to match your sandboxes to the number of sandboxes that you purchased. For
example, if you have two Full sandboxes but purchased only one, you cant refresh your Full sandbox as a Full
sandbox. Instead, you must choose a Full sandbox to convert to a smaller sandbox, such as a Developer Pro or a
Developer sandbox, depending on which types you have available.
5. Select the data you want to include in your sandbox (you have this option for a Partial Copy or Full sandbox).
For a Partial Copy sandbox, select the template you created to specify the data for your sandbox. If you have not created
a template for this Partial Copy sandbox, see Creating or Editing Sandbox Templates in the Salesforce Help.
For a Full sandbox, you can choose to include Template-based data for a Full sandbox. For this option, you need to have
already created a sandbox template. Then you can pick the template from a list of templates youve created. For more
information, see Creating or Editing Sandbox Templates in the Salesforce Help.
For a Full sandbox, choose how much object history, case history, and opportunity history to copy, and whether or not to
copy Chatter data. Object history is the field history tracking of custom and most standard objects; case history and
opportunity history serve the same purpose for cases and opportunities. You can copy from 0 to 180 days of history, in
30-day increments. The default value is 0 days. Chatter data includes feeds, messages, and discovery topics. Decreasing
the amount of data you copy can significantly speed up sandbox copy time.
6. Click Create.
The process may take several minutes, hours, or even days, depending on the size and type of your organization.
Tip: Try to limit changes in your production organization while the sandbox copy proceeds.

Learning Apex
After you have your developer account, there are many resources available to you for learning about Apex:
Force.com Workbook: Get Started Building Your First App in the Cloud
Beginning programmers
A set of ten 30-minute tutorials that introduce various Force.com platform features. The Force.com Workbook tutorials
are centered around building a very simple warehouse management system. You'll start developing the application from
the bottom up; that is, you'll first build a database model for keeping track of merchandise. You'll continue by adding
business logic: validation rules to ensure that there is enough stock, workflow to update inventory when something is
sold, approvals to send email notifications for large invoice values, and trigger logic to update the prices in open invoices.
Once the database and business logic are complete, you'll create a user interface to display a product inventory to staff,
a public website to display a product catalog, and then the start of a simple store front. If you'd like to develop offline
and integrate with the app, we've added a final tutorial to use Adobe Flash Builder for Force.com.
Force.com Workbook: HTML | PDF

14

Apex Development Process

Learning Apex

Apex Workbook
Beginning programmers
The Apex Workbook introduces you to the Apex programming language through a set of tutorials. Youll learn the
fundamentals of Apex and how you can use it on the Force.com platform to add custom business logic through triggers,
unit tests, scheduled Apex, batch Apex, REST Web services, and Visualforce controllers.
Apex Workbook: HTML | PDF
Developer Force Apex Page
Beginning and advanced programmers
The Apex page on Developer Force has links to several resources including articles about the Apex programming language.
These resources provide a quick introduction to Apex and include best practices for Apex development.
Force.com Cookbook
Beginning and advanced programmers
This collaborative site provides many recipes for using the Web services API, developing Apex code, and creating
Visualforce pages. The Force.com Cookbook helps developers become familiar with common Force.com programming
techniques and best practices. You can read and comment on existing recipes, or submit your own recipes, at
http://developer.force.com/cookbook.
Development Life Cycle: Enterprise Development on the Force.com Platform
Architects and advanced programmers
Whether you are an architect, administrator, developer, or manager, the Development Life Cycle Guide prepares you to
undertake the development and release of complex applications on the Force.com platform.
Training Courses
Training classes are also available from salesforce.com Training & Certification. You can find a complete list of courses
at the Training & Certification site.
In This Book (Apex Developer's Guide)
Beginning programmers should look at the following:
Introducing Apex, and in particular:
Documentation Conventions
Core Concepts
Quick Start Tutorial

Classes, Objects, and Interfaces


Testing Apex
Understanding Execution Governors and Limits

In addition to the above, advanced programmers should look at:


Trigger and Bulk Request Best Practices
Advanced Apex Programming Example
Understanding Apex Describe Information
Asynchronous Execution (@future Annotation)
Batch Apex and Apex Scheduler

15

Apex Development Process

Writing Apex Using Development Environments

Writing Apex Using Development Environments


There are several development environments for developing Apex code. The Force.com Developer Console and the Force.com
IDE allow you to write, test, and debug your Apex code. The code editor in the user interface enables only writing code and
doesnt support debugging. These different tools are described in the next sections.

Force.com Developer Console


The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and
test applications in your Salesforce organization.
To open the Developer Console in Salesforce user interface, click Your name > Developer Console.
The Developer Console supports these tasks:

Writing codeYou can add code using the source code editor. Also, you can browse packages in your organization.
Compiling codeWhen you save a trigger or class, the code is automatically compiled. Any compilation errors will be
reported.
DebuggingYou can view debug logs and set checkpoints that aid in debugging.
TestingYou can execute tests of specific test classes or all tests in your organization, and you can view test results. Also,
you can inspect code coverage.
Checking performanceYou can inspect debug logs to locate performance bottlenecks.
SOQL queriesYou can query data in your organization and view the results using the Query Editor.
Color coding and autocompleteThe source code editor uses a color scheme for easier readability of code elements and
provides autocompletion for class and method names.

Force.com IDE
The Force.com IDE is a plug-in for the Eclipse IDE. The Force.com IDE provides a unified interface for building and
deploying Force.com applications. Designed for developers and development teams, the IDE provides tools to accelerate
Force.com application development, including source code editors, test execution tools, wizards and integrated help. This tool
includes basic color-coding, outline view, integrated unit testing, and auto-compilation on save with error message display.
See the website for information about installation and usage.
Note: The Force.com IDE is a free resource provided by salesforce.com to support its users and partners but isn't
considered part of our services for purposes of the salesforce.com Master Subscription Agreement.
Tip: If you want to extend the Eclipse plug-in or develop an Apex IDE of your own, the SOAP API includes methods
for compiling triggers and classes, and executing test methods, while the Metadata API includes methods for deploying
code to production environments. For more information, see Deploying Apex on page 407 and SOAP API and SOAP
Headers for Apex on page 1640.

Code Editor in the Salesforce User Interface


The Salesforce user interface. All classes and triggers are compiled when they are saved, and any syntax errors are flagged. You
cannot save your code until it compiles without errors. The Salesforce user interface also numbers the lines in the code, and
uses color coding to distinguish different elements, such as comments, keywords, literal strings, and so on.

For a trigger on a standard object, from Setup, click Customize, click the name of the object, and click Triggers. In the
Triggers detail page, click New, and then enter your code in the Body text box.
For a trigger on a custom object, from Setup, click Develop > Objects, and click the name of the object. In the Triggers
related list, click New, and then enter your code in the Body text box.
For a class, from Setup, click Develop > Apex Classes. Click New, and then enter your code in the Body text box.

16

Apex Development Process

Writing Tests

Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.

Alternatively, you can use any text editor, such as Notepad, to write Apex code. Then either copy and paste the code into your
application, or use one of the API calls to deploy it.

Writing Tests
Testing is the key to successful long-term development and is a critical component of the development process. We strongly
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
development.
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are
class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit
no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the
method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest.
In addition, before you deploy Apex or package it for the Force.com AppExchange, the following must be true.

At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is
covered. Instead, you should make sure that every use case of your application is covered, including positive and negative
cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.

Every trigger must have some test coverage.


All classes and triggers must compile successfully.

For more information on writing tests, see Testing Apex on page 384.

Deploying Apex to a Sandbox Organization


sandboxes give you the ability to create multiple copies of your organization in separate environments for a variety of purposes,
such as development, testing, and training, without compromising the data and applications in your Salesforce production
organization. Sandboxes are isolated from your Salesforce production organization, so operations that you perform in your
sandboxes dont affect your Salesforce production organization, and vice versa.
To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component
Deployment Wizard. For more information about the Force.com IDE, see
https://developer.salesforce.com/page/Force.com_IDE.
You can also use the deploy() Metadata API call to deploy your Apex from a developer organization to a sandbox organization.
A useful API call is runTests(). In a development or sandbox organization, you can run the unit tests for a specific class, a
list of classes, or a namespace.
Salesforce includes a Force.com Migration Tool that allows you to issue these commands in a console window, or your can
implement your own deployment code.

17

Apex Development Process

Deploying Apex to a Salesforce Production Organization

Note: The Force.com IDE and the Force.com Migration Tool are free resources provided by salesforce.com to
support its users and partners, but aren't considered part of our services for purposes of the salesforce.com Master
Subscription Agreement.
For more information, see Using the Force.com Migration Tool and Deploying Apex.

Deploying Apex to a Salesforce Production Organization


After you have finished all of your unit tests and verified that your Apex code is executing properly, the final step is deploying
Apex to your Salesforce production organization.
To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component
Deployment Wizard. For more information about the Force.com IDE, see
https://developer.salesforce.com/page/Force.com_IDE.
Also, you can deploy Apex through change sets in the Salesforce user interface.
For more information and for additional deployment options, see Deploying Apex on page 407.

Adding Apex Code to a Force.com AppExchange App


You can also include an Apex class or trigger in an app that you are creating for AppExchange.
Any Apex that is included as part of a package must have at least 75% cumulative test coverage. Each trigger must also have
some test coverage. When you upload your package to AppExchange, all tests are run to ensure that they run without errors.
In addition, tests with the@isTest(OnInstall=true) annotation run when the package is installed in the installer's
organization. You can specify which tests should run during package install by annotating them with
@isTest(OnInstall=true). This subset of tests must pass for the package install to succeed.
In addition, salesforce.com recommends that any AppExchange package that contains Apex be a managed package.
For more information, see the Force.com Quick Reference for Developing Packages. For more information about Apex in managed
packages, see What is a Package? in the Salesforce online help.
Note: Packaging Apex classes that contain references to custom labels which have translations: To include the
translations in the package, enable the Translation Workbench and explicitly package the individual languages used
in the translated custom labels. See Custom Labels Overview in the Salesforce online help.

18

Chapter 3
Apex Quick Start
Once you have a Developer Edition or sandbox organization, you may want to learn some of the core concepts of Apex.
Because Apex is very similar to Java, you may recognize much of the functionality.
After reviewing the basics, you are ready to write your first Apex programa very simple class, trigger, and unit test.
In addition, there is a more complex shipping invoice example that you can also walk through. This example illustrates many
more features of the language.
Note: The Hello World and the shipping invoice samples require custom fields and objects. You can either create
these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com
AppExchange. For more information, see https://developer.salesforce.com/docs.

Writing Your First Apex Class and Trigger


This step-by-step tutorial shows how to create a simple Apex class and trigger. It also shows how to deploy these components
to a production organization.
This tutorial is based on a custom object called Book that is created in the first step. This custom object is updated through
a trigger.
Creating a Custom Object
Adding an Apex Class
Adding an Apex Trigger
Adding a Test Class
Deploying Components to Production

Creating a Custom Object


Prerequisites:
A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a Developer
organization.
For more information about creating a sandbox organization, see Sandbox Overview in the Salesforce online help. To sign
up for a free Developer organization, see the Developer Edition Environment Sign Up Page.
In this step, you create a custom object called Book with one custom field called Price.
1.
2.
3.
4.

Log into your sandbox or Developer organization.


From Setup, click Create > Objects and click New Custom Object.
Enter Book for the label.
Enter Books for the plural label.
19

Apex Quick Start

Adding an Apex Class

5. Click Save.
Ta dah! You've now created your first custom object. Now let's create a custom field.
6. In the Custom Fields & Relationships section of the Book detail page, click New.
7. Select Number for the data type and click Next.
8. Enter Price for the field label.
9. Enter 16 in the length text box.
10. Enter 2 in the decimal places text box, and click Next.
11. Click Next to accept the default values for field-level security.
12. Click Save.
Youve just created a custom object called Book, and added a custom field to that custom object. Custom objects already have
some standard fields, like Name and CreatedBy, and allow you to add other fields that are more specific to your implementation.
For this tutorial, the Price field is part of our Book object and it is accessed by the Apex class you will write in the next step.

Adding an Apex Class


Prerequisites:

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a


Developer organization.
The Book custom object.

In this step, you add an Apex class that contains a method for updating the book price. This method is called by the trigger
that you will be adding in the next step.
1. From Setup, click Develop > Apex Classes and click New.
2. In the class editor, enter this class definition:
public class MyHelloWorld {
}

The previous code is the class definition to which you will be adding one method in the next step. Apex code is generally
contained in classes. This class is defined as public, which means the class is available to other Apex classes and triggers.
For more information, see Classes, Objects, and Interfaces on page 53.
3. Add this method definition between the class opening and closing brackets.
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}

This method is called applyDiscount, and it is both public and static. Because it is a static method, you don't need to
create an instance of the class to access the methodyou can just use the name of the class followed by a dot (.) and the
name of the method. For more information, see Static and Instance on page 60.
This method takes one parameter, a list of Book records, which is assigned to the variable books. Notice the __c in the
object name Book__c. This indicates that it is a custom object that you created. Standard objects that are provided in the
Salesforce application, such as Account, don't end with this postfix.

20

Apex Quick Start

Adding an Apex Trigger

The next section of code contains the rest of the method definition:
for (Book__c b :books){
b.Price__c *= 0.9;
}

Notice the __c after the field name Price__c. This indicates it is a custom field that you created. Standard fields that are
provided by default in Salesforce are accessed using the same type of dot notation but without the __c, for example, Name
doesn't end with __c in Book__c.Name. The statement b.Price__c *= 0.9; takes the old value of b.Price__c,
multiplies it by 0.9, which means its value will be discounted by 10%, and then stores the new value into the b.Price__c
field. The *= operator is a shortcut. Another way to write this statement is b.Price__c = b.Price__c * 0.9;. See
Understanding Expression Operators on page 39.
4. Click Save to save the new class. You should now have this full class definition.
public class MyHelloWorld {
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
}

You now have a class that contains some code that iterates over a list of books and updates the Price field for each book. This
code is part of the applyDiscount static method called by the trigger that you will create in the next step.

Adding an Apex Trigger


Prerequisites:

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a


Developer organization.
The MyHelloWorld Apex class.

In this step, you create a trigger for the Book__c custom object that calls the applyDiscount method of the MyHelloWorld
class that you created in the previous step.
A trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the
Force.com platform database. Every trigger runs with a set of context variables that provide access to the records that caused
the trigger to fire. All triggers run in bulk; that is, they process several records at once.
1. From Setup, click Create > Objects and click the name of the object you just created, Book.
2. In the triggers section, click New.
3. In the trigger editor, delete the default template code and enter this trigger definition:
trigger HelloWorldTrigger on Book__c (before insert) {
Book__c[] books = Trigger.new;
MyHelloWorld.applyDiscount(books);
}

The first line of code defines the trigger:


trigger HelloWorldTrigger on Book__c (before insert) {

21

Apex Quick Start

Adding a Test Class

It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example,
this trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into
the database.
The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context
variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and
provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that
are about to be inserted.
Book__c[] books = Trigger.new;

The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new
books.
MyHelloWorld.applyDiscount(books);

You now have all the code that is needed to update the price of all books that get inserted. However, there is still one piece
of the puzzle missing. Unit tests are an important part of writing code and are required. In the next step, you will see why this
is so and you will be able to add a test class.

Adding a Test Class


Prerequisites:

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a


Developer organization.
The HelloWorldTrigger Apex trigger.

In this step, you add a test class with one test method. You also run the test and verify code coverage. The test method exercises
and validates the code in the trigger and class. Also, it enables you to reach 100% code coverage for the trigger and class.
Note: Testing is an important part of the development process. Before you can deploy Apex or package it for the
Force.com AppExchange, the following must be true.

At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code
that is covered. Instead, you should make sure that every use case of your application is covered, including
positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code
being covered by unit tests.

Every trigger must have some test coverage.


All classes and triggers must compile successfully.

1. From Setup, click Develop > Apex Classes and click New.
2. In the class editor, add this test class definition, and then click Save.
@isTest
private class HelloWorldTestClass {

22

Apex Quick Start

Adding a Test Class

static testMethod void validateHelloWorld() {


Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);
}
}

This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage
to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3
MB for all Apex code. You can also add the @isTest annotation to individual methods. For more information, see IsTest
Annotation on page 80 and Understanding Execution Governors and Limits.
The method validateHelloWorld is defined as a testMethod. This means that if any changes are made to the
database, they are automatically rolled back when execution completes and you don't have to delete any test data created
in the test method.
First the test method creates a new book and inserts it into the database temporarily. The System.debug statement writes
the value of the price in the debug log.
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;

Once the book is inserted, the code retrieves the newly inserted book, using the ID that was initially assigned to the book
when it was inserted, and then logs the new price that the trigger modified:
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);

When the MyHelloWorld class runs, it updates the Price__c field and reduces its value by 10%. The following line is
the actual test, verifying that the method applyDiscount actually ran and produced the expected result:
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);

3. Now lets switch to the Developer Console to run this test and view code coverage information. Click Your Name >
Developer Console.
The Developer Console window opens.
4. In the Developer Console, click Test > New Run.
5. To add your test class, click HelloWorldTestClass, and then click >.
6. To run the test, click Run.
The test result displays in the Tests tab. Optionally, you can expand the test class in the Tests tab to view which methods
were run. In this case, the class contains only one test method.

23

Apex Quick Start

Deploying Components to Production

7. The Overall Code Coverage pane shows the code coverage of this test class. To view the lines of code in the trigger covered
by this test, which is 100%, double-click the code coverage line for HelloWorldTrigger. Also, because the trigger calls a
method from the MyHelloWorld class, this class has some coverage too (100%). To view the class coverage, double-click
MyHelloWorld.
8. To open the log file, in the Logs tab, double-click the most recent log line in the list of logs. The execution log displays,
including logging information about the trigger event, the call to the applyDiscount class method, and the debug output
of the price before and after the trigger.
By now, you have completed all the steps necessary for writing some Apex code with a test that runs in your development
environment. In the real world, after youve sufficiently tested your code and youre satisfied with it, you want to deploy the
code along with any other prerequisite components to a production organization. The next step will show you how to do this
for the code and custom object youve just created.

Deploying Components to Production


Prerequisites:

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization.


The HelloWorldTestClass Apex test class.
A deployment connection between the sandbox and production organizations that allows inbound change sets to be received
by the production organization. See Change Sets Overview in the Salesforce online help.
Create and Upload Change Sets user permission to create, edit, or upload outbound change sets.

In this step, you deploy the Apex code and the custom object you created previously to your production organization using
change sets.
This procedure doesn't apply to Developer organizations since change sets are available only in Performance, Unlimited,
Enterprise, or Database.com Edition organizations. If you have a Developer Edition account, you can use other deployment
methods. For more information, see Deploying Apex.
1.
2.
3.
4.
5.
6.

From Setup, click Deploy > Outbound Changesets.


If a splash page appears, click Continue.
In the Change Sets list, click New.
Enter a name for your change set, for example, HelloWorldChangeSet, and optionally a description. Click Save.
In the Change Set Components section, click Add.
Select Apex Class from the component type drop-down list, then select the MyHelloWorld and the HelloWorldTestClass
classes from the list and click Add to Change Set.
7. Click View/Add Dependencies to add the dependent components.
8. Select the top checkbox to select all components. Click Add To Change Set.
9. In the Change Set Detail section of the change set page, click Upload.
10. Select the target organization, in this case production, and click Upload.
11. After the change set upload completes, deploy it in your production organization.
a.
b.
c.
d.
e.

Log into your production organization.


From Setup, click Deploy > Inbound Change Sets.
If a splash page appears, click Continue.
In the change sets awaiting deployment list, click your change set's name.
Click Deploy.

In this tutorial, you learned how to create a custom object, how to add an Apex trigger, class, and test class. Finally, you also
learned how to test your code, and how to upload the code and the custom object using Change Sets.

24

WRITING APEX

Chapter 4
Data Types and Variables
In this chapter ...

Data Types
Primitive Data Types
Collections
Enums
Variables
Constants
Expressions and Operators
Assignment Statements
Understanding Rules of Conversion

In this chapter youll learn about data types and variables in Apex. Youll also
learn about related language constructsenums, constants, expressions,
operators, and assignment statements.

25

Data Types and Variables

Data Types

Data Types
In Apex, all variables and expressions have a data type that is one of the following:

A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types on page
26)
An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c
(see sObject Types on page 100 in Chapter 4.)
A collection, including:
A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists
on page 29)
A set of primitives (see Sets on page 32)
A map from a primitive to a primitive, sObject, or collection (see Maps on page 32)

A typed list of values, also known as an enum (see Enums on page 34)
Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 53)
Objects created from system supplied Apex classes
Null (for the null constant, which can be assigned to any variable)

Methods can return values of any of the listed types, or return no value and be of type Void.
Type checking is strictly enforced at compile time. For example, the parser generates an error if an object field of type Integer
is assigned a value of type String. However, all compile-time exceptions are returned as specific fault codes, with the line
number and column of the error. For more information, see Debugging Apex on page 354.

Primitive Data Types


Apex uses the same primitive data types as the SOAP API. All primitive data types are passed by value.
All Apex variables, whether theyre class member variables or method variables, are initialized to null. Make sure that you
initialize your variables to appropriate values before using them. For example, initialize a Boolean variable to false.
Apex primitive data types include:
Data Type

Description

Blob

A collection of binary data stored as a single object. You can convert this datatype to String
or from String using the toString and valueOf methods, respectively. Blobs can be accepted
as Web service arguments, stored in a document (the body of a document is a Blob), or sent
as attachments. For more information, see Crypto Class.

Boolean

A value that can only be assigned true, false, or null. For example:
Boolean isWinner = true;

Date

A value that indicates a particular day. Unlike Datetime values, Date values contain no
information about time. Date values must always be created with a system static method.
You cannot manipulate a Date value, such as add days, merely by adding a number to a Date
variable. You must use the Date methods instead.

26

Data Types and Variables

Primitive Data Types

Data Type

Description

Datetime

A value that indicates a particular day and time, such as a timestamp. Datetime values must
always be created with a system static method.
You cannot manipulate a Datetime value, such as add minutes, merely by adding a number
to a Datetime variable. You must use the Datetime methods instead.

Decimal

A number that includes a decimal point. Decimal is an arbitrary precision number. Currency
fields are automatically assigned the type Decimal.
If you do not explicitly set the scale, that is, the number of decimal places, for a Decimal using
the setScale method, the scale is determined by the item from which the Decimal is created.

Double

If the Decimal is created as part of a query, the scale is based on the scale of the field
returned from the query.
If the Decimal is created from a String, the scale is the number of characters after the
decimal point of the String.
If the Decimal is created from a non-decimal number, the scale is determined by converting
the number to a String and then using the number of characters after the decimal point.

A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and
a maximum value of 263-1. For example:
Double d=3.14159;

Note that scientific notation (e) for Doubles is not supported.


ID

Any valid 18-character Force.com record identifier. For example:


ID id='00300000003T2PGAA0';

Note that if you set ID to a 15-character value, Apex automatically converts the value to its
18-character representation. All invalid ID values are rejected with a runtime exception.
Integer

A 32-bit number that does not include a decimal point. Integers have a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647. For example:
Integer i = 1;

Long

A 64-bit number that does not include a decimal point. Longs have a minimum value of -263
and a maximum value of 263-1. Use this datatype when you need a range of values wider than
those provided by Integer. For example:
Long l = 2147483648L;

Object

Any data type that is supported in Apexprimitive data types (such as Integer), user-defined
custom classes, the sObject generic type, or an sObject specific type (such as Account). All
Apex data types inherit from Object.

27

Data Types and Variables

Data Type

Primitive Data Types

Description
You can cast an object that represents a more specific data type to its underlying data type.
For example:
Object obj = 10;
// Cast the object to an integer.
Integer i = (Integer)obj;
System.assertEquals(10, i);

The next example shows how to cast an object to a user-defined typea custom Apex class
named MyApexClass that is predefined in your organization.
Object obj = new MyApexClass();
// Cast the object to the MyApexClass custom type.
MyApexClass mc = (MyApexClass)obj;
// Access a method on the user-defined class.
mc.someClassMethod();

String

Any set of characters surrounded by single quotes. For example,


String s = 'The quick brown fox jumped over the lazy dog.';

String size: Strings have no limit on the number of characters they can include. Instead, the
heap size limit is used to ensure that your Apex programs don't grow too large.
Empty Strings and Trailing Whitespace: sObject String field values follow the same rules
as in the SOAP API: they can never be empty (only null), and they can never include leading
and trailing whitespace. These conventions are necessary for database storage.
Conversely, Strings in Apex can be null or empty, and can include leading and trailing
whitespace (such as might be used to construct a message).
The Solution sObject field SolutionNote operates as a special type of String. If you have
HTML Solutions enabled, any HTML tags used in this field are verified before the object
is created or updated. If invalid HTML is entered, an error is thrown. Any JavaScript used
in this field is removed before the object is created or updated. In the following example,
when the Solution displays on a detail page, the SolutionNote field has H1 HTML formatting
applied to it:
trigger t on Solution (before insert) {
Trigger.new[0].SolutionNote ='<h1>hello</h1>';
}

In the following example, when the Solution displays on a detail page, the SolutionNote field
only contains HelloGoodbye:
trigger t2 on Solution (before insert) {
Trigger.new[0].SolutionNote =
'<javascript>Hello</javascript>Goodbye';
}

For more information, see HTML Solutions Overview in the Salesforce online help.

28

Data Types and Variables

Collections

Data Type

Description
Escape Sequences: All Strings in Apex use the same escape sequences as SOQL strings: \b
(backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote),
\' (single quote), and \\ (backslash).
Comparison Operators: Unlike Java, Apex Strings support use of the comparison operators
==, !=, <, <=, >, and >=. Since Apex uses SOQL comparison semantics, results for Strings
are collated according to the context user's locale, and `are not case sensitive. For more
information, see Operators on page 39.
String Methods: As in Java, Strings can be manipulated with a number of standard methods.
See String Class for information.
Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a
runtime error if you assign a String value that is too long for the field.

Time

A value that indicates a particular time. Time values must always be created with a system
static method. See Time Class.

In addition, two non-standard primitive data types cannot be used as variable or method types, but do appear in system static
methods:

AnyType. The valueOf static method converts an sObject field of type AnyType to a standard primitive. AnyType is
used within the Force.com platform database exclusively for sObject fields in field history tracking tables.
Currency. The Currency.newInstance static method creates a literal of type Currency. This method is for use solely
within SOQL and SOSL WHERE clauses to filter against sObject currency fields. You cannot instantiate Currency in any
other type of Apex.

For more information on the AnyType data type, see Field Types in the Object Reference for Salesforce and Force.com.

Collections
Apex has the following types of collections:

Lists
Maps
Sets
Note: There is no limit on the number of items a collection can hold. However, there is a general limit on heap size.

Lists
A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data typeprimitive
types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table is a visual representation
of a list of Strings:
Index 0

Index 1

Index 2

Index 3

Index 4

Index 5

'Red'

'Orange'

'Yellow'

'Green'

'Blue'

'Purple'

29

Data Types and Variables

Lists

The index position of the first element in a list is always 0.


Lists can contain any collection and can be nested within one another and become multidimensional. For example, you can
have a list of lists of sets of Integers. A list can contain up to four levels of nested collections inside it, that is, a total of five
levels overall.
To declare a list, use the List keyword followed by the primitive data, sObject, nested list, map, or set type within <> characters.
For example:
// Create an empty list of String
List<String> my_list = new List<String>();
// Create a nested list
List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>();

To access elements in a list, use the List methods provided by Apex. For example:
List<Integer> myList = new List<Integer>(); // Define a new list
myList.add(47);
// Adds a second element of value 47 to the end
// of the list
Integer i = myList.get(0);
// Retrieves the element at index 0
myList.set(0, 1);
// Adds the integer 1 to the list at index 0
myList.clear();
// Removes all elements from the list

For more information, including a complete list of all supported methods, see List Class on page 1357.
Using Array Notation for One-Dimensional Lists
When using one-dimensional lists of primitives or objects, you can also use more traditional array notation to declare and
reference list elements. For example, you can declare a one-dimensional list of primitives or objects by following the data type
name with the [] characters:
String[] colors = new List<String>();

These two statements are equivalent to the previous:


List<String> colors = new String[1];
String[] colors = new String[1];

To reference an element of a one-dimensional list, you can also follow the name of the list with the element's index position
in square brackets. For example:
colors[0] = 'Green';

Even though the size of the previous String array is defined as one element (the number between the brackets in new
String[1]), lists are elastic and can grow as needed provided that you use the List add method to add new elements. For
example, you can add two or more elements to the colors list. But if youre using square brackets to add an element to a list,
the list behaves like an array and isnt elastic, that is, you wont be allowed to add more elements than the declared array size.
All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example:
Example

Description
Defines an Integer list of size zero with no elements

List<Integer> ints = new Integer[0];

30

Data Types and Variables

Lists

Example

Description
Defines an Integer list with memory allocated for six Integers

List<Integer> ints = new Integer[6];

List Sorting
You can sort list elements and the sort order depends on the data type of the elements.
Using the List.sort method, you can sort elements in a list. Sorting is in ascending order for elements of primitive data
types, such as strings. The sort order of other more complex data types is described in the chapters covering those data types.
This example shows how to sort a list of strings and verifies that the colors are in ascending order in the list.
List<String> colors = new List<String>{
'Yellow',
'Red',
'Green'};
colors.sort();
System.assertEquals('Green', colors.get(0));
System.assertEquals('Red', colors.get(1));
System.assertEquals('Yellow', colors.get(2));

For the Visualforce SelectOption control, sorting is in ascending order based on the value and label fields. See this next section
for the sequence of comparison steps used for SelectOption.
Default Sort Order for SelectOption
The List.sort method sorts SelectOption elements in ascending order using the value and label fields, and is based on this
comparison sequence.
1. The value field is used for sorting first.
2. If two value fields have the same value or are both empty, the label field is used.
Note that the disabled field is not used for sorting.
For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.
In this example, a list contains three SelectOption elements. Two elements, United States and Mexico, have the same value
field (A). The List.sort method sorts these two elements based on the label field, and places Mexico before United States,
as shown in the output. The last element in the sorted list is Canada and is sorted on its value field C, which comes after A.
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('A','United States'));
options.add(new SelectOption('C','Canada'));
options.add(new SelectOption('A','Mexico'));
System.debug('Before sorting: ' + options);
options.sort();
System.debug('After sorting: ' + options);

This is the output of the debug statements. It shows the list contents before and after the sort.
DEBUG|Before sorting: (System.SelectOption[value="A", label="United States",
disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"],
System.SelectOption[value="A", label="Mexico", disabled="false"])
DEBUG|After sorting: (System.SelectOption[value="A", label="Mexico", disabled="false"],
System.SelectOption[value="A", label="United States", disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"])

31

Data Types and Variables

Sets

Sets
A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data typeprimitive
types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table represents a set of
strings, that uses city names:
'San Francisco'

'New York'

'Paris'

'Tokyo'

Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers.
A set can contain up to four levels of nested collections inside it, that is, up to five levels overall.
To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
new Set<String>()

The following are ways to declare and populate a set:


Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the
// elements of the set created in the previous step

To access elements in a set, use the system methods provided by Apex. For example:
Set<Integer> s = new Set<Integer>();
s.add(1);
System.assert(s.contains(1));
s.remove(1);

//
//
//
//

Define
Add an
Assert
Remove

a new set
element to the set
that the set contains an element
the element from the set

For more information, including a complete list of all supported set system methods, see Set Class on page 1461.
Note the following limitations on sets:

Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations
(for example, HashSet or TreeSet). Apex uses a hash structure for all sets.
A set is an unordered collection. Do not rely on the order in which set results are returned. The order of objects returned
by sets may change without warning.

Maps
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data
typeprimitive types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table
represents a map of countries and currencies:
Country (Key)

'United States'

'Japan'

'France'

'England'

'India'

Currency (Value)

'Dollar'

'Yen'

'Euro'

'Pound'

'Rupee'

Map keys and values can contain any collection, and can contain nested collections. For example, you can have a map of
Integers to maps, which, in turn, map Strings to lists. Map keys can contain up to only four levels of nested collections.

32

Data Types and Variables

Parameterized Typing

To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
Map<String, String> country_currencies = new Map<String, String>();
Map<ID, Set<String>> m = new Map<ID, Set<String>>();

You can use the generic or specific sObject data types with maps (youll learn more about maps with sObjects in a later chapter).
You can also create a generic instance of a map.
As with lists, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the
curly braces, specify the key first, then specify the value for that key using =>. For example:
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' =>
'd'.toUpperCase()};

In the first example, the value for the key a is b, and the value for the key c is d.
To access elements in a map, use the Map methods provided by Apex. This example creates a map of integer keys and string
values. It adds two entries, checks for the existence of the first key, retrieves the value for the second entry, and finally gets the
set of all keys.
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry');
// Insert a new key-value pair in the map
m.put(2, 'Second entry');
// Insert a new key-value pair in the map
System.assert(m.containsKey(1)); // Assert that the map contains a key
String value = m.get(2);
// Retrieve a value, given a particular key
System.assertEquals('Second entry', value);
Set<Integer> s = m.keySet();
// Return a set that contains all of the keys in the
map

For more information, including a complete list of all supported Map methods, see Map Class on page 1371.
Map Considerations

Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations
(for example, HashMap or TreeMap). Apex uses a hash structure for all maps.
Do not rely on the order in which map results are returned. The order of objects returned by maps may change without
warning. Always access map elements by key.
A map key can hold the null value.
Adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with
the new entry.
Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding
distinct Map entries. Subsequently, the Map methods, including put, get, containsKey, and remove treat these keys
as distinct.
Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods, which you provide
in your classes. Uniqueness of keys of all other non-primitive types, such as sObject keys, is determined by comparing the
objects field values.

Parameterized Typing
Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable
before that variable can be used. For example, the following is legal in Apex:
Integer x = 1;

33

Data Types and Variables

Enums

The following is not legal if x has not been defined earlier:


x = 1;

Lists, maps and sets are parameterized in Apex: they take any data type Apex supports for them as an argument. That data
type must be replaced with an actual data type upon construction of the list, map or set. For example:
List<String> myList = new List<String>();

Subtyping with Parameterized Lists


In Apex, if type T is a subtype of U, then List<T> would be a subtype of List<U>. For example, the following is legal:
List<String> slst = new List<String> {'foo', 'bar'};
List<Object> olst = slst;

Enums
An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums
are typically used to define a set of possible values that dont otherwise have a numerical order, such as the suit of a card, or a
particular season of the year. Although each value corresponds to a distinct integer value, the enum hides this implementation
so that you dont inadvertently misuse the values, such as using them to perform arithmetic. After you create an enum, variables,
method arguments, and return types can be declared of that type.
Note: Unlike Java, the enum type itself has no constructor syntax.

To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values.
For example, the following code creates an enum called Season:
public enum Season {WINTER, SPRING, SUMMER, FALL}

By creating the enum Season, you have also created a new data type called Season. You can use this new data type as you
might any other data type. For example:
Season e = Season.WINTER;
Season m(Integer x, Season e) {
if (e == Season.SUMMER) return e;
//...
}

You can also define a class as an enum. Note that when you create an enum class you do not use the class keyword in the
definition.
public enum MyEnumClass { X, Y }

You can use an enum in any place you can use another data type name. If you define a variable whose type is an enum, any
object you assign to it must be an instance of that enum class.

34

Data Types and Variables

Enums

Any webService methods can use enum types as part of their signature. When this occurs, the associated WSDL file includes
definitions for the enum and its values, which can then be used by the API client.
Apex provides the following system-defined enums:

System.StatusCode

This enum corresponds to the API error code that is exposed in the WSDL document for all API operations. For example:
StatusCode.CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
StatusCode.INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY

The full list of status codes is available in the WSDL file for your organization. For more information about accessing the
WSDL file for your organization, see Downloading Salesforce WSDLs and Client Authentication Certificates in the
Salesforce online help.

System.XmlTag:

This enum returns a list of XML tags used for parsing the result XML from a webService method. For more information,
see XmlStreamReader Class.

System.ApplicationReadWriteMode: This enum indicates if an organization is in 5 Minute Upgrade read-only mode


during Salesforce upgrades and downtimes. For more information, see Using the System.ApplicationReadWriteMode

Enum.

System.LoggingLevel:

This enum is used with the system.debug method, to specify the log level for all debug calls. For more information,
see System Class.

System.RoundingMode:

This enum is used by methods that perform mathematical operations to specify the rounding behavior for the operation,
such as the Decimal divide method and the Double round method. For more information, see Rounding Mode.

System.SoapType:

This enum is returned by the field describe result getSoapType method. For more informations, see SOAPType Enum.

System.DisplayType:

This enum is returned by the field describe result getType method. For more information, see DisplayType Enum.

System.JSONToken:

This enum is used for parsing JSON content. For more information, see JSONToken Enum.

ApexPages.Severity:

This enum specifies the severity of a Visualforce message. For more information, see ApexPages.Severity Enum.

Dom.XmlNodeType:

This enum specifies the node type in a DOM document.


Note: System-defined enums cannot be used in Web service methods.

All enum values, including system enums, have common methods associated with them. For more information, see Enum
Methods.

35

Data Types and Variables

Variables

You cannot add user-defined methods to enum values.

Variables
Local variables are declared with Java-style syntax. For example:
Integer i = 0;
String str;
List<String> strList;
Set<String> s;
Map<ID, String> m;

As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
Integer i, j, k;

Null Variables and Initial Values


If you declare a variable and don't initialize it with a value, it will be null. In essence, null means the absence of a value.
You can also assign null to any variable declared with a primitive type. For example, both of these statements result in a
variable set to null:
Boolean x = null;
Decimal d;

Many instance methods on the data type will fail if the variable is null. In this example, the second statement generates an
exception (NullPointerException)
Date d;
d.addDays(2);

All variables are initialized to null if they arent assigned a value. For instance, in the following example, i, and k are assigned
values, while the integer variable j and the boolean variable b are set to null because they arent explicitly initialized.
Integer i = 0, j, k = 1;
Boolean b;

Note: A common pitfall is to assume that an uninitialized boolean variable is initialized to false by the system.
This isnt the case. Like all other variables, boolean variables are null if not assigned a value explicitly.

Variable Scope
Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks cant redefine a variable
name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:
Integer i;
{
// Integer i;
}

This declaration is not allowed

for (Integer j = 0; j < 10; j++);


for (Integer j = 0; j < 10; j++);

36

Data Types and Variables

Constants

Case Sensitivity
To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means:

Variable and method names are case-insensitive. For example:


Integer I;
//Integer i;

This would be an error.

References to object and field names are case-insensitive. For example:


Account a1;
ACCOUNT a2;

SOQL and SOSL statements are case- insensitive. For example:


Account[] accts = [sELect ID From ACCouNT where nAme = 'fred'];

Note: Youll learn more about sObjects, SOQL and SOSL later in this guide.

Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the SOAP API and
the Salesforce user interface. The use of these semantics can lead to some interesting behavior. For example, if an end-user
generates a report based on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned
in the result. The rationale for this behavior is that users typically think of a field without a value as just a space character,
rather than its actual null value. Consequently, in Apex, the following expressions all evaluate to true:
String s;
System.assert('a' == 'A');
System.assert(s < 'b');
System.assert(!(s > 'b'));

Note: Although s < 'b' evaluates to true in the example above, 'b.'compareTo(s) generates an error because
youre trying to compare a letter to a null value.

Constants
Apex constants are variables whose values dont change after being initialized once.
Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in
the declaration itself, or with a static initializer method if the constant is defined in a class. This example declares two constants.
The first is initialized in the declaration statement. The second is assigned a value in a static block by calling a static method.
public class myCls {
static final Integer PRIVATE_INT_CONST = 200;
static final Integer PRIVATE_INT_CONST2;
public static Integer calculate() {
return 2 + 7;
}
static {
PRIVATE_INT_CONST2 = calculate();

37

Data Types and Variables

Expressions and Operators

}
}

For more information, see Using the final Keyword on page 74.

Expressions and Operators


An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. This
section provides an overview of expressions in Apex and contains the following:

Understanding Expressions
Understanding Expression Operators
Understanding Operator Precedence
Expanding sObject and List Expressions
Using Comments

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:


1 + 1

A new sObject, Apex object, list, set, or map. For example:


new
new
new
new
new
new
new

Account(<field_initializers>)
Integer[<n>]
Account[]{<elements>}
List<Account>()
Set<String>{}
Map<String, Integer>()
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.

38

Data Types and Variables

Understanding Expression Operators

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 on page 127.


A static or instance method invocation. For example:

System.assert(true)
myRenamingClass.replaceNames()
changePoint(new Point(x, y));

Understanding Expression Operators


Expressions can also be joined to one another with operators to create compound expressions. Apex supports the following
operators:
Operator

Syntax

Description

x = y

Assignment operator (Right associative). Assigns the value of y to the L-value


x. Note that the data type of x must match the data type of y, and cannot be
null.

+=

x += y

Addition assignment operator (Right associative). Adds the value of y to


the original value of x and then reassigns the new value to x. See + for
additional information. x and y cannot be null.

*=

x *= y

Multiplication assignment operator (Right associative). Multiplies the value


of y with the original value of x and then reassigns the new value to x. Note
that x and y must be Integers or Doubles, or a combination. x and y cannot
be null.

-=

x -= y

Subtraction assignment operator (Right associative). Subtracts the value of


y from the original value of x and then reassigns the new value to x. Note
that x and y must be Integers or Doubles, or a combination. x and y cannot
be null.

/=

x /= y

Division assignment operator (Right associative). Divides the original value


of x with the value of y and then reassigns the new value to x. Note that x
and y must be Integers or Doubles, or a combination. x and y cannot be
null.

|=

x |= y

OR assignment operator (Right associative). If x, a Boolean, and y, a Boolean,


are both false, then x remains false. Otherwise, x is assigned the value of true.
Note:

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is false.
x and y cannot be null.

39

Data Types and Variables

Understanding Expression Operators

Operator

Syntax

Description

&=

x &= y

AND assignment operator (Right associative). If x, a Boolean, and y, a


Boolean, are both true, then x remains true. Otherwise, x is assigned the value
of false.
Note:

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is true.
x and y cannot be null.

<<=

x <<= y

Bitwise shift left assignment operator. Shifts each bit in x to the left by y
bits so that the high order bits are lost, and the new right bits are set to 0.
This value is then reassigned to x.

>>=

x >>= y

Bitwise shift right signed assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for positive values of y and 1 for negative values of y. This value is then
reassigned to x.

>>>=

x >>>= y

Bitwise shift right unsigned assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for all values of y. This value is then reassigned to x.

? :

x ? y : z

Ternary operator (Right associative). This operator acts as a short-hand for


if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z
is the result. Note that x cannot be null.

&&

x && y

AND logical operator (Left associative). If x, a Boolean, and y, a Boolean,


are both true, then the expression evaluates to true. Otherwise the expression
evaluates to false.
Note:

||

x || y

&& has precedence over ||

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is true.
x and y cannot be null.

OR logical operator (Left associative). If x, a Boolean, and y, a Boolean, are


both false, then the expression evaluates to false. Otherwise the expression
evaluates to true.
Note:

&& has precedence over ||

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is false.
x and y cannot be null.

40

Data Types and Variables

Understanding Expression Operators

Operator

Syntax

Description

==

x == y

Equality operator. If the value of x equals the value of y, the expression


evaluates to true. Otherwise, the expression evaluates to false.
Note:

Unlike Java, == in Apex compares object value equality, not reference


equality, except for user-defined types. Consequently:
String comparison using == is case insensitive
ID comparison using == is case sensitive, and does not distinguish
between 15-character and 18-character formats
User-defined types are compared by reference, which means that two
objects are equal only if they reference the same location in memory.
You can override this default comparison behavior by providing equals
and hashCode methods in your class to compare object values instead.

For sObjects and sObject arrays, == performs a deep check of all sObject
field values before returning its result. Likewise for collections and built-in
Apex objects.
For records, every field must have the same value for == to evaluate to
true.
x or y can be the literal null.
The comparison of any two values can never result in null.
SOQL and SOSL use = for their equality operator, and not ==. Although
Apex and SOQL and SOSL are strongly linked, this unfortunate syntax
discrepancy exists because most modern languages use = for assignment
and == for equality. The designers of Apex deemed it more valuable to
maintain this paradigm than to force developers to learn a new assignment
operator. The result is that Apex developers must use == for equality tests
in the main body of the Apex code, and = for equality in SOQL and SOSL
queries.

===

x === y

Exact equality operator. If x and y reference the exact same location in


memory, the expression evaluates to true. Otherwise, the expression evaluates
to false.

<

x < y

Less than operator. If x is less than y, the expression evaluates to true.


Otherwise, the expression evaluates to false.
Note:

Unlike other database stored procedures, Apex does not support tri-state
Boolean logic, and the comparison of any two values can never result in
null.
If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.

41

Data Types and Variables

Operator

Syntax

Understanding Expression Operators

Description

>

x > y

x and y cannot be Booleans.

The comparison of two strings is performed according to the locale of the


context user.

Greater than operator. If x is greater than y, the expression evaluates to true.


Otherwise, the expression evaluates to false.
Note:

<=

x <= y

The comparison of any two values can never result in null.


If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Less than or equal to operator. If x is less than or equal to y, the expression


evaluates to true. Otherwise, the expression evaluates to false.
Note:

>=

x >= y

The comparison of any two values can never result in null.


If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Greater than or equal to operator. If x is greater than or equal to y, the


expression evaluates to true. Otherwise, the expression evaluates to false.
Note:

The comparison of any two values can never result in null.


If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
42

Data Types and Variables

Operator

Syntax

Understanding Expression Operators

Description

!=

x != y

x and y cannot be Booleans.

The comparison of two strings is performed according to the locale of the


context user.

Inequality operator. If the value of x does not equal the value of y, the
expression evaluates to true. Otherwise, the expression evaluates to false.
Note:

Unlike Java, != in Apex compares object value equality, not reference


equality, except for user-defined types.
For sObjects and sObject arrays, != performs a deep check of all sObject
field values before returning its result.
For records, != evaluates to true if the records have different values for
any field.
User-defined types are compared by reference, which means that two
objects are different only if they reference different locations in memory.
You can override this default comparison behavior by providing equals
and hashCode methods in your class to compare object values instead.
x or y can be the literal null.
The comparison of any two values can never result in null.

!==

x !== y

Exact inequality operator. If x and y do not reference the exact same location
in memory, the expression evaluates to true. Otherwise, the expression evaluates
to false.

x + y

Addition operator. Adds the value of x to the value of y according to the


following rules:
If x and y are Integers or Doubles, adds the value of x to the value of y.
If a Double is used, the result is a Double.
If x is a Date and y is an Integer, returns a new Date that is incremented
by the specified number of days.
If x is a Datetime and y is an Integer or Double, returns a new Date that
is incremented by the specified number of days, with the fractional portion
corresponding to a portion of a day.
If x is a String and y is a String or any other type of non-null argument,
concatenates y to the end of x.

x - y

Subtraction operator. Subtracts the value of y from the value of x according


to the following rules:
If x and y are Integers or Doubles, subtracts the value of y from the value
of x. If a Double is used, the result is a Double.
If x is a Date and y is an Integer, returns a new Date that is decremented
by the specified number of days.
If x is a Datetime and y is an Integer or Double, returns a new Date that
is decremented by the specified number of days, with the fractional portion
corresponding to a portion of a day.

x * y

Multiplication operator. Multiplies x, an Integer or Double, with y, another


Integer or Double. Note that if a double is used, the result is a Double.

43

Data Types and Variables

Understanding Operator Precedence

Operator

Syntax

Description

x / y

Division operator. Divides x, an Integer or Double, by y, another Integer or


Double. Note that if a double is used, the result is a Double.

!x

Logical complement operator. Inverts the value of a Boolean, so that true


becomes false, and false becomes true.

-x

Unary negation operator. Multiplies the value of x, an Integer or Double,


by -1. Note that the positive equivalent + is also syntactically valid, but does
not have a mathematical effect.

++

x++

Increment operator. Adds 1 to the value of x, a variable of a numeric type.


If prefixed (++x), the expression evaluates to the value of x after the increment.
If postfixed (x++), the expression evaluates to the value of x before the
increment.

++x

--

x---x

Decrement operator. Subtracts 1 from the value of x, a variable of a numeric


type. If prefixed (--x), the expression evaluates to the value of x after the
decrement. If postfixed (x--), the expression evaluates to the value of x before
the decrement.

&

x & y

Bitwise AND operator. ANDs each bit in x with the corresponding bit in y
so that the result bit is set to 1 if both of the bits are set to 1. This operator
is not valid for types Long or Integer.

x | y

Bitwise OR operator. ORs each bit in x with the corresponding bit in y so


that the result bit is set to 1 if at least one of the bits is set to 1. This operator
is not valid for types Long or Integer.

x ^ y

Bitwise exclusive OR operator. Exclusive ORs each bit in x with the


corresponding bit in y so that the result bit is set to 1 if exactly one of the bits
is set to 1 and the other bit is set to 0.

^=

x ^= y

Bitwise exclusive OR operator. Exclusive ORs each bit in x with the


corresponding bit in y so that the result bit is set to 1 if exactly one of the bits
is set to 1 and the other bit is set to 0. Assigns the result of the exclusive OR
operation to x.

<<

x << y

Bitwise shift left operator. Shifts each bit in x to the left by y bits so that the
high order bits are lost, and the new right bits are set to 0.

>>

x >> y

Bitwise shift right signed operator. Shifts each bit in x to the right by y bits
so that the low order bits are lost, and the new left bits are set to 0 for positive
values of y and 1 for negative values of y.

>>>

x >>> y

Bitwise shift right unsigned operator. Shifts each bit in x to the right by y
bits so that the low order bits are lost, and the new left bits are set to 0 for all
values of y.

()

(x)

Parentheses. Elevates the precedence of an expression x so that it is evaluated


first in a compound expression.

Understanding Operator Precedence


Apex uses the following operator precedence rules:
44

Data Types and Variables

Using Comments

Precedence

Operators

Description

{} () ++ --

Grouping and prefix increments and decrements

! -x +x (type) new

Unary negation, type cast and object creation

* /

Multiplication and division

+ -

Addition and subtraction

< <= > >= instanceof

Greater-than and less-than comparisons, reference


tests

== !=

Comparisons: equal and not-equal

&&

Logical AND

||

Logical OR

= += -= *= /= &=

Assignment operators

Using Comments
Both single and multiline comments are supported in Apex code:

To create a single line comment, use //. All characters on the same line to the right of the // are ignored by the parser.
For example:
Integer i = 1; // This comment is ignored by the parser

To create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. For example:
Integer i = 1; /* This comment can wrap over multiple
lines without getting interpreted by the
parser. */

Assignment Statements
An assignment statement is any statement that places a value into a variable, generally in one of the following two forms:
[LValue] = [new_value_expression];
[LValue] = [[inline_soql_query]];

In the forms above, [LValue] stands for any expression that can be placed on the left side of an assignment operator. These
include:

A simple variable. For example:


Integer i = 1;
Account a = new Account();
Account[] accts = [SELECT Id FROM Account];

45

Data Types and Variables

Understanding Rules of Conversion

A de-referenced list element. For example:


ints[0] = 1;
accts[0].Name = 'Acme';

An sObject field reference that the context user has permission to edit. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
// IDs cannot be set prior to an insert call
// a.Id = '00300000003T2PGAA0';
// Instead, insert the record. The system automatically assigns it an ID.
insert a;
// Fields also must be writeable for the context user
// a.CreatedDate = System.today(); This code is invalid because
//
createdDate is read-only!
// Since the account a has been inserted, it is now possible to
// create a new contact that is related to it
Contact c = new Contact(LastName = 'Roth', Account = a);
// Notice that you can write to the account name directly through the contact
c.Account.Name = 'salesforce.com';

Assignment is always done by reference. For example:


Account a = new Account();
Account b;
Account[] c = new Account[]{};
a.Name = 'Acme';
b = a;
c.add(a);
// These asserts should now be true. You can reference the data
// originally allocated to account a through account b and account list c.
System.assertEquals(b.Name, 'Acme');
System.assertEquals(c[0].Name, 'Acme');

Similarly, two lists can point at the same value in memory. For example:
Account[] a = new Account[]{new Account()};
Account[] b = a;
a[0].Name = 'Acme';
System.assert(b[0].Name == 'Acme');

In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Understanding Expression
Operators on page 39.

Understanding Rules of Conversion


In general, Apex requires you to explicitly convert one data type to another. For example, a variable of the Integer data type
cannot be implicitly converted to a String. You must use the string.format method. However, a few data types can be
implicitly converted, without using a method.
Numbers form a hierarchy of types. Variables of lower numeric types can always be assigned to higher types without explicit
conversion. The following is the hierarchy for numbers, from lowest to highest:
46

Data Types and Variables

1.
2.
3.
4.

Understanding Rules of Conversion

Integer
Long
Double
Decimal
Note: Once a value has been passed from a number of a lower type to a number of a higher type, the value is converted
to the higher type of number.

Note that the hierarchy and implicit conversion is unlike the Java hierarchy of numbers, where the base interface number is
used and implicit object conversion is never allowed.
In addition to numbers, other data types can be implicitly converted. The following rules apply:

IDs can always be assigned to Strings.


Strings can be assigned to IDs. However, at runtime, the value is checked to ensure that it is a legitimate ID. If it is not,
a runtime exception is thrown.
The instanceOf keyword can always be used to test whether a string is an ID.

Additional Considerations for Data Types


Data Types of Numeric Values
Numeric values represent Integer values unless they are appended with L for a Long or with .0 for a Double or Decimal.
For example, the expression Long d = 123; declares a Long variable named d and assigns it to an Integer numeric
value (123), which is implicitly converted to a Long. The Integer value on the right hand side is within the range for
Integers and the assignment succeeds. However, if the numeric value on the right hand side exceeds the maximum value
for an Integer, you get a compilation error. In this case, the solution is to append L to the numeric value so that it
represents a Long value which has a wider range, as shown in this example: Long d = 2147483648L;.
Overflow of Data Type Values
Arithmetic computations that produce values larger than the maximum value of the current type are said to overflow.
For example, Integer i = 2147483647 + 1; yields a value of 2147483648 because 2147483647 is the maximum
value for an Integer, so adding one to it wraps the value around to the minimum negative value for Integers, 2147483648.
If arithmetic computations generate results larger than the maximum value for the current type, the end result will be
incorrect because the computed values that are larger than the maximum will overflow. For example, the expression
Long MillsPerYear = 365 * 24 * 60 * 60 * 1000; results in an incorrect result because the products of
Integers on the right hand side are larger than the maximum Integer value and they overflow. As a result, the final
product isn't the expected one. You can avoid this by ensuring that the type of numeric values or variables you are using
in arithmetic operations are large enough to hold the results. In this example, append L to numeric values to make them
Long so the intermediate products will be Long as well and no overflow occurs. The following example shows how to
correctly compute the amount of milliseconds in a year by multiplying Long numeric values.
Long MillsPerYear = 365L * 24L * 60L * 60L * 1000L;
Long ExpectedValue = 31536000000L;
System.assertEquals(MillsPerYear, ExpectedValue);

Loss of Fractions in Divisions


When dividing numeric Integer or Long values, the fractional portion of the result, if any, is removed before performing
any implicit conversions to a Double or Decimal. For example, Double d = 5/3; returns 1.0 because the actual result
(1.666...) is an Integer and is rounded to 1 before being implicitly converted to a Double. To preserve the fractional
value, ensure that you are using Double or Decimal numeric values in the division. For example, Double d = 5.0/3.0;
returns 1.6666666666666667 because 5.0 and 3.0 represent Double values, which results in the quotient being a Double
as well and no fractional value is lost.

47

Chapter 5
Control Flow Statements
In this chapter ...

Apex provides statements that control the flow of code execution.

Statements are generally executed line by line, in the order they appear. With
control flow statements, you can cause Apex code to execute based on a certain
condition or you can have a block of code execute repeatedly. This section
describes these control flow statements: if-else statements and loops.

Conditional (If-Else) Statements


Loops

48

Control Flow Statements

Conditional (If-Else) Statements

Conditional (If-Else) Statements


The conditional statement in Apex works similarly to Java:
if ([Boolean_condition])
// Statement 1
else
// Statement 2

The else portion is always optional, and always groups with the closest if. For example:
Integer x, sign;
// Your code
if (x <= 0) if (x == 0) sign = 0; else sign = -1;

is equivalent to:
Integer x, sign;
// Your code
if (x <= 0) {
if (x == 0) {
sign = 0;
} else {
sign = -1;
}
}

Repeated else if statements are also allowed. For example:


if (place == 1) {
medal_color = 'gold';
} else if (place == 2) {
medal_color = 'silver';
} else if (place == 3) {
medal_color = 'bronze';
} else {
medal_color = null;
}

Loops
Apex supports the following five types of procedural loops:

do {statement} while (Boolean_condition);


while (Boolean_condition) statement;
for (initialization; Boolean_exit_condition; increment) statement;
for (variable : array_or_set) statement;
for (variable : [inline_soql_query]) statement;

All loops allow for loop control structures:

break; exits the entire loop


continue; skips to the next iteration of the loop

49

Control Flow Statements

Do-While Loops

Do-While Loops
The Apex do-while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
do {
code_block
} while (condition);

Note: Curly braces ({}) are always required around a code_block.

As in Java, the Apex do-while loop does not check the Boolean condition statement until after the first loop is executed.
Consequently, the code block always runs at least once.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
do {
System.debug(count);
count++;
} while (count < 11);

While Loops
The Apex while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
while (condition) {
code_block
}

Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Unlike do-while, the while loop checks the Boolean condition statement before the first loop is executed. Consequently,
it is possible for the code block to never execute.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
while (count < 11) {
System.debug(count);
count++;
}

For Loops
Apex supports three variations of the for loop:
50

Control Flow Statements

For Loops

The traditional for loop:


for (init_stmt; exit_condition; increment_stmt) {
code_block
}

The list or set iteration for loop:


for (variable : list_or_set) {
code_block
}

where variable must be of the same primitive or sObject type as list_or_set.

The SOQL for loop:


for (variable : [soql_query]) {
code_block
}

or
for (variable_list : [soql_query]) {
code_block
}

Both variable and variable_list must be of the same sObject type as is returned by the soql_query.
Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Each is discussed further in the sections that follow.

Traditional For Loops


The traditional for loop in Apex corresponds to the traditional syntax used in Java and other languages. Its syntax is:
for (init_stmt; exit_condition; increment_stmt) {
code_block
}

When executing this type of for loop, the Apex runtime engine performs the following steps, in order:
1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this
statement.
2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits.
3. Execute the code_block.
4. Execute the increment_stmt statement.
5. Return to Step 2.

51

Control Flow Statements

For Loops

As an example, the following code outputs the numbers 1 - 10 into the debug log. Note that an additional initialization variable,
j, is included to demonstrate the syntax:
for (Integer i = 0, j = 0; i < 10; i++) {
System.debug(i+1);
}

List or Set Iteration for Loops


The list or set iteration for loop iterates over all the elements in a list or set. Its syntax is:
for (variable : list_or_set) {
code_block
}

where variable must be of the same primitive or sObject type as list_or_set.


When executing this type of for loop, the Apex runtime engine assigns variable to each element in list_or_set, and
runs the code_block for each value.
For example, the following code outputs the numbers 1 - 10 to the debug log:
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (Integer i : myInts) {
System.debug(i);
}

Iterating Collections
Collections can consist of lists, sets, or maps. Modifying a collection's elements while iterating through that collection is not
supported and causes an error. Do not directly add or remove elements while iterating through the collection that includes
them.
Adding Elements During Iteration
To add elements while iterating a list, set or map, keep the new elements in a temporary list, set, or map and add them to the
original after you finish iterating the collection.
Removing Elements During Iteration
To remove elements while iterating a list, create a new list, then copy the elements you wish to keep. Alternatively, add the
elements you wish to remove to a temporary list and remove them after you finish iterating the collection.
Note:
The List.remove method performs linearly. Using it to remove elements has time and resource implications.
To remove elements while iterating a map or set, keep the keys you wish to remove in a temporary list, then remove them
after you finish iterating the collection.

52

Chapter 6
Classes, Objects, and Interfaces
In this chapter ...

Understanding Classes
Understanding Interfaces
Keywords
Annotations
Classes and Casting
Differences Between Apex Classes and
Java Classes
Class Definition Creation
Namespace Prefix
Apex Code Versions
Lists of Custom Types and Sorting
Using Custom Types in Map Keys and
Sets

This chapter covers classes and interfaces in Apex. It describes defining classes,
instantiating them, and extending them. Interfaces, Apex class versions,
properties, and other related class concepts are also described.
In most cases, the class concepts described here are modeled on their
counterparts in Java, and can be quickly understood by those who are familiar
with them.

53

Classes, Objects, and Interfaces

Understanding Classes

Understanding Classes
As in Java, you can create classes in Apex. A class is a template or blueprint from which objects are created. An object is an
instance of a class. For example, the PurchaseOrder class describes an entire purchase order, and everything that you can
do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive.
All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. The state
of a PurchaseOrder objectwhat it knowsincludes the user who sent it, the date and time it was created, and whether it
was flagged as important. The behavior of a PurchaseOrder objectwhat it can doincludes checking inventory, shipping
a product, or notifying a customer.
A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or
Type. Since these variables are associated with a class and are members of it, they are commonly referred to as member variables.
Methods are used to control behavior, such as getOtherQuotes or copyLineItems.
A class can contain other classes, exception types, and initialization code.
An interface is like a class in which none of the methods have been implementedthe method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
For more general information on classes, objects, and interfaces, see
http://java.sun.com/docs/books/tutorial/java/concepts/index.html

Apex Class Definition


In Apex, you can define top-level classes (also called outer classes) as well as inner classes, that is, a class defined within another
class. You can only have inner classes one level deep. For example:
public class myOuterClass {
// Additional myOuterClass code here
class myInnerClass {
// myInnerClass code here
}
}

To define a class, specify the following:


1. Access modifiers:

You must use one of the access modifiers (such as public or global) in the declaration of a top-level class.
You do not have to use an access modifier in the declaration of an inner class.

2. Optional definition modifiers (such as virtual, abstract, and so on)


3. Required: The keyword class followed by the name of the class
4. Optional extensions and/or implementations
Note: Avoid using standard object names for class names. Doing so causes unexpected results. For a list of standard
objects, see Object Reference for Salesforce and Force.com.
Use the following syntax for defining classes:
private | public | global
[virtual | abstract | with sharing | without sharing | (none)]

54

Classes, Objects, and Interfaces

Class Variables

class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)]


{
// The body of the class
}

The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the
default access for inner classesthat is, if you don't specify an access modifier for an inner class, it is considered private.
This keyword can only be used with inner classes.
The public access modifier declares that this class is visible in your application or namespace.
The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods
defined with the webService keyword must be declared as global. If a method or inner class is declared as global,
the outer, top-level class must also be defined as global.
The with sharing and without sharing keywords specify the sharing mode for this class. For more information,
see Using the with sharing or without sharing Keywords on page 77.
The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method
with the override keyword unless the class has been defined as virtual.
The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their
signature declared and no body defined.
Note:

You cannot add an abstract method to a global class after the class has been uploaded in a Managed - Released
package version.
If the class in the Managed - Released package is virtual, the method that you can add to it must also be virtual
and must have an implementation.
You cannot override a public or protected virtual method of a global class of an installed managed package.

For more information about managed packages, see What is a Package? on page 415.
A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support
multiple inheritance. The interface names in the list are separated by commas. For more information about interfaces, see
Understanding Interfaces on page 70.
For more information about method and variable access modifiers, see Access Modifiers on page 59.

Class Variables
To declare a variable, specify the following:

Optional: Modifiers, such as public or final, as well as static.


Required: The data type of the variable, such as String or Boolean.
Required: The name of the variable.
Optional: The value of the variable.

Use the following syntax when defining a variable:


[public | private | protected | global | final] [static] data_type variable_name
[= value]

55

Classes, Objects, and Interfaces

Class Methods

For example:
private static final Integer MY_INT;
private final Integer i = 1;

Class Methods
To define a method, specify the following:

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.

Use the following syntax when defining a method:


(public | private | protected | global ) [override] [static] data_type method_name
(input parameters)
{
// The body of the method
}

Note: You can only use override to override methods in classes that have been defined as virtual.

For example:
public static Integer getInt() {
return MY_INT;
}

As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable.
Note that user-defined methods:

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
on page 421.
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 on page 46.

56

Classes, Objects, and Interfaces

Class Methods

Note: If the parser finds multiple approximate matches, a parse-time exception is generated.

When using void methods that have side effects, user-defined methods are typically executed as stand-alone procedure
statements in Apex code. For example:
System.debug('Here is a note for the log.');

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
This example shows how a primitive argument of type String is passed by value into another method. The
debugStatusMessage method in this example creates a String variable, msg, and assigns it a value. It then passes this
variable as an argument to another method, which modifies the value of this String. However, since String is a primitive type,
it is passed by value, and when the method returns, the value of the original variable, msg, is unchanged. An assert statement
verifies that the value of msg is still the old value.
public class PassPrimitiveTypeExample {
public static void debugStatusMessage() {
String msg = 'Original value';
processString(msg);
// The value of the msg variable didn't
// change; it is still the old value.
System.assertEquals(msg, 'Original value');
}
public static void processString(String s) {
s = 'Modified value';
}
}

Example: Passing Non-Primitive Data Type Arguments


This example shows how a List argument is passed by value into another method and can be modified. It also shows that the
List argument cant be modified to point to another List object. First, the createTemperatureHistory method creates
a variable, fillMe, that is a List of Integers and passes it to a method. The called method fills this list with Integer values
representing rounded temperature values. When the method returns, an assert verifies that the contents of the original List
variable has changed and now contains five values. Next, the example creates a second List variable, createMe, and passes it
to another method. The called method assigns the passed-in argument to a newly created List that contains new Integer values.
When the method returns, the original createMe variable doesnt point to the new List but still points to the original List,
which is empty. An assert verifies that createMe contains no values.
public class PassNonPrimitiveTypeExample {

57

Classes, Objects, and Interfaces

Using Constructors

public static void createTemperatureHistory() {


List<Integer> fillMe = new List<Integer>();
reference(fillMe);
// The list is modified and contains five items
// as expected.
System.assertEquals(fillMe.size(),5);
List<Integer> createMe = new List<Integer>();
referenceNew(createMe);
// The list is not modified because it still points
// to the original list, not the new list
// that the method created.
System.assertEquals(createMe.size(),0);
}
public static void reference(List<Integer> m) {
// Add rounded temperatures for the last five days.
m.add(70);
m.add(68);
m.add(75);
m.add(80);
m.add(82);
}
public static void referenceNew(List<Integer> m) {
// Assign argument to a new List of
// five temperature values.
m = new List<Integer>{55, 59, 62, 60, 63};
}
}

Using Constructors
A constructor is code that is invoked when an object is created from the class blueprint. You do not need to write a constructor
for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return
type and it is not inherited by the object created from it.
After you write the constructor for a class, you must use the new keyword in order to instantiate an object from that class,
using that constructor. For example, using the following class:
public class TestObject {
// The no argument constructor
public TestObject() {
// more code here
}
}

A new object of this type can be instantiated with the following code:
TestObject myTest = new TestObject();

If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments.
If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one
in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor.
You must create your own.

58

Classes, Objects, and Interfaces

Access Modifiers

In Apex, a constructor can be overloaded, that is, there can be more than one constructor for a class, each having different
parameters. The following example illustrates a class with two constructors: one with no arguments and one that takes a simple
Integer argument. It also illustrates how one constructor calls another constructor using the this(...) syntax, also know as
constructor chaining.
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
}
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;
}
}

New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(42);
TestObject2 myObject2 = new TestObject2();

Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors
are possible:
public class Leads {
// First a no-argument constructor
public Leads () {}
// A constructor with one argument
public Leads (Boolean call) {}
// A constructor with two arguments
public Leads (String email, Boolean call) {}
// Though this constructor has the same arguments as the
// one above, they are in a different order, so this is legal
public Leads (Boolean call, String email) {}
}

When you define a new class, you are defining a new data type. You can use class name in any place you can use other data
type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must
be an instance of that class or subclass.

Access Modifiers
Apex allows you to use the private, protected, public, and global access modifiers when defining methods and
variables.
While triggers and anonymous blocks can also use these access modifiers, they are not as useful in smaller portions of Apex.
For example, declaring a method as global in an anonymous block does not enable you to call it from outside of that code.
For more information on class access modifiers, see Apex Class Definition on page 54.
59

Classes, Objects, and Interfaces

Static and Instance

Note: Interface methods have no access modifiers. They are always global. For more information, see Understanding
Interfaces on page 70.
By default, a method or variable is visible only to the Apex code within the defining class. You must explicitly specify a method
or variable as public in order for it to be available to other classes in the same application namespace (see Namespace Prefix).
You can change the level of visibility by using the following access modifiers:
private

This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined.
If you do not specify an access modifier, the method or variable is private.
protected

This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that
extend the defining Apex class. You can only use this access modifier for instance methods and member variables. Note
that it is strictly more permissive than the default (private) setting, just like Java.
public

This means the method or variable can be used by any Apex in this application or namespace.
Note: In Apex, the public access modifier is not the same as it is in Java. This was done to discourage joining
applications, to keep the code for each application separate. In Apex, if you want to make something public like
it is in Java, you need to use the global access modifier.

global

This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in
the same application. This access modifier should be used for any method that needs to be referenced outside of the
application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must
also declare the class that contains it as global.
Note: We recommend using the global access modifier rarely, if at all. Cross-application dependencies are
difficult to maintain.

To use the private, protected, public, or global access modifiers, use the following syntax:
[(none)|private|protected|public|global] declaration

For example:
private string s1 = '1';
public string gets1() {
return this.s1;
}

Static and Instance


In Apex, you can have static methods, variables, and initialization code. Apex classes cant be static. You can also have instance
methods, member variables, and initialization code (which have no modifier), and local variables:

60

Classes, Objects, and Interfaces

Static and Instance

Static methods, variables, or initialization code are associated with a class, and are only allowed in outer classes. When you
declare a method or variable as static, it's initialized only once when a class is loaded. Static variables aren't transmitted
as part of the view state for a Visualforce page.
Instance methods, member variables, and initialization code are associated with a particular object and have no definition
modifier. When you declare instance methods, member variables, or initialization code, an instance of that item is created
with every object instantiated from the class.
Local variables are associated with the block of code in which they are declared. All local variables should be initialized
before they are used.

The following is an example of a local variable whose scope is the duration of the if code block:
Boolean myCondition = true;
if (myCondition) {
integer localVariable = 10;
}

Using Static Methods and Variables


You can only use static methods and variables with outer classes. Inner classes have no static methods or variables. A static
method or variable does not require an instance of the class in order to run.
All static member variables in a class are initialized before any object of the class is created. This includes any static initialization
code blocks. All of these are run in the order in which they appear in the class.
Static methods are generally used as utility methods and never depend on a particular instance member variable value. Because
a static method is only associated with a class, it cannot access any instance member variable values of its class.
Static variables are only static within the scope of the request. Theyre not static across the server, or across the entire organization.
Use static variables to store information that is shared within the confines of the class. All instances of the same class share a
single copy of the static variables. For example, all triggers that are spawned by the same transaction can communicate with
each other by viewing and updating static variables in a related class. A recursive trigger might use the value of a class variable
to determine when to exit the recursion.
Suppose you had the following class:
public class p {
public static boolean firstRun = true;
}

A trigger that uses this class could then selectively fail the first run of the trigger:
trigger t1 on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}

Static variables defined in a trigger dont retain their values between different trigger contexts within the same transaction, for
example, between before insert and after insert invocations. Define the static variables in a class instead so that the trigger can
access these class member variables and check their static values.
Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an
instance of C, then x.S is not a legal expression.

61

Classes, Objects, and Interfaces

Static and Instance

The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to
those static identifiers using the class: C.S and C.M().
If a local variable is named the same as the class name, these static methods and variables are hidden.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword).
Note: For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the
chunk of 200 records to process is further split into chunks of 100 records. For Apex saved using Salesforce.com API
version 21.0 and later, no further splits of API chunks occur. Note that static variable values are reset between API
batches, but governor limits are not. Do not use static variables to track state information between API batches.
Using Instance Methods and Variables
Instance methods and member variables are used by an instance of a class, that is, by an object. Instance member variables are
declared inside a class, but not within a method. Instance methods usually use instance member variables to affect the behavior
of the method.
Suppose you wanted to have a class that collects two dimensional points and plot them on a graph. The following skeleton
class illustrates this, making use of member variables to hold the list of points and an inner class to manage the two-dimensional
list of points.
public class Plotter {
// This inner class manages the points
class Point {
Double x;
Double y;
Point(Double x, Double y) {
this.x = x;
this.y = y;
}
Double getXCoordinate() {
return x;
}
Double getYCoordinate() {
return y;
}
}
List<Point> points = new List<Point>();
public void plot(Double x, Double y) {
points.add(new Point(x, y));
}
// The following method takes the list of points and does something with them
public void render() {
}
}

Using Initialization Code


Instance initialization code is a block of code in the following form that is defined in a class:
{
//code body
}

62

Classes, Objects, and Interfaces

Apex Properties

The instance initialization code in a class is executed every time an object is instantiated from that class. These code blocks
run before the constructor.
If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize
instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor
to do initialization and not use instance initialization code.
Static initialization code is a block of code preceded with the keyword static:
static {
//code body
}

Similar to other static code, a static initialization code block is only initialized once on the first use of the class.
A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body.
The code blocks are executed in the order in which they appear in the file, the same as in Java.
You can use static initialization code to initialize static final variables and to declare any information that is static, such as a
map of values. For example:
public class MyClass {
class RGB {
Integer red;
Integer green;
Integer blue;
RGB(Integer red, Integer green, Integer blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
}
static Map<String, RGB> colorMap = new Map<String, RGB>();
static {
colorMap.put('red', new RGB(255, 0, 0));
colorMap.put('cyan', new RGB(0, 255, 255));
colorMap.put('magenta', new RGB(255, 0, 255));
}
}

Apex Properties
An Apex property is similar to a variable, however, you can do additional things in your code to a property value before it is
accessed or returned. Properties can be used in many different ways: they can validate data before a change is made; they can
prompt an action when data is changed, such as altering the value of other member variables; or they can expose data that is
retrieved from some other source, such as another class.
Property definitions include one or two code blocks, representing a get accessor and a set accessor:

The code in a get accessor executes when the property is read.


The code in a set accessor executes when the property is assigned a new value.

A property with only a get accessor is considered read-only. A property with only a set accessor is considered write-only. A
property with both accessors is read-write.
63

Classes, Objects, and Interfaces

Apex Properties

To declare a property, use the following syntax in the body of a class:


Public class BasicClass {
// Property declaration
access_modifier return_type property_name {
get {
//Get accessor code block
}
set {
//Set accessor code block
}
}
}

Where:

access_modifier is the access modifier for the property. The access modifiers that can be applied to properties include:
public, private, global, and protected. In addition, these definition modifiers can be applied: static and
transient. For more information on access modifiers, see Access Modifiers on page 59.

return_type is the type of the property, such as Integer, Double, sObject, and so on. For more information, see Data

Types on page 26.


property_name is the name of the property

For example, the following class defines a property named prop. The property is public. The property returns an integer data
type.
public class BasicProperty {
public integer prop {
get { return prop; }
set { prop = value; }
}
}

The following code segment calls the class above, exercising the get and set accessors:
BasicProperty bp = new BasicProperty();
bp.prop = 5;
// Calls set accessor
System.assert(bp.prop == 5);
// Calls get accessor

Note the following:

The body of the get accessor is similar to that of a method. It must return a value of the property type. Executing the get
accessor is the same as reading the value of the variable.
The get accessor must end in a return statement.
We recommend that your get accessor should not change the state of the object that it is defined on.
The set accessor is similar to a method whose return type is void.
When you assign a value to the property, the set accessor is invoked with an argument that provides the new value.
When the set accessor is invoked, the system passes an implicit argument to the setter called value of the same data type
as the property.
Properties cannot be defined on interface.
Apex properties are based on their counterparts in C#, with the following differences:
Properties provide storage for values directly. You do not need to create supporting members for storing values.
It is possible to create automatic properties in Apex. For more information, see Using Automatic Properties on page
65.
64

Classes, Objects, and Interfaces

Apex Properties

Using Automatic Properties


Properties do not require additional code in their get or set accessor code blocks. Instead, you can leave get and set accessor
code blocks empty to define an automatic property. Automatic properties allow you to write more compact code that is easier
to debug and maintain. They can be declared as read-only, read-write, or write-only. The following example creates three
automatic properties:
public class AutomaticProperty {
public integer MyReadOnlyProp { get; }
public double MyReadWriteProp { get; set; }
public string MyWriteOnlyProp { set; }
}

The following code segment exercises these properties:


AutomaticProperty ap = new AutomaticProperty();
ap.MyReadOnlyProp = 5;
// This produces a compile error: not writable
ap.MyReadWriteProp = 5;
// No error
System.assert(MyWriteOnlyProp == 5);
// This produces a compile error: not readable

Using Static Properties


When a property is declared as static, the property's accessor methods execute in a static context. This means that the
accessors do not have access to non-static member variables defined in the class. The following example creates a class with
both static and instance properties:
public class StaticProperty {
public static integer StaticMember;
public integer NonStaticMember;
public static integer MyGoodStaticProp {
get{return MyGoodStaticProp;}
}
// The following produces a system error
// public static integer MyBadStaticProp { return NonStaticMember; }
public integer MyGoodNonStaticProp {
get{return NonStaticMember;}
}
}

The following code segment calls the static and instance properties:
StaticProperty sp = new StaticProperty();
// The following produces a system error: a static variable cannot be
// accessed through an object instance
// sp.MyGoodStaticProp = 5;
// The following does not produce an error
StaticProperty.MyGoodStaticProp = 5;

Using Access Modifiers on Property Accessors


Property accessors can be defined with their own access modifiers. If an accessor includes its own access modifier, this modifier
overrides the access modifier of the property. The access modifier of an individual accessor must be more restrictive than the
access modifier on the property itself. For example, if the property has been defined as public, the individual accessor cannot
be defined as global. The following class definition shows additional examples:
global virtual class PropertyVisibility {
// X is private for read and public for write
public integer X { private get; set; }

65

Classes, Objects, and Interfaces

Extending a Class

// Y can be globally read but only written within a class


global integer Y { get; public set; }
// Z can be read within the class but only subclasses can set it
public integer Z { get; protected set; }
}

Extending a Class
You can extend a class to provide a more specialized behavior.
A class that extends another class inherits all the methods and properties of the extended class. In addition, the extending class
can override the existing virtual methods by using the override keyword in the method definition. Overriding a virtual method
allows you to provide a different implementation for an existing method. This means that the behavior of a particular method
is different based on the object youre calling it on. This is referred to as polymorphism.
A class extends another class using the extends keyword in the class definition. A class can only extend one other class, but
it can implement more than one interface.
This example shows how to extend a class. The YellowMarker class extends the Marker class.
public virtual class Marker {
public virtual void write() {
System.debug('Writing some text.');
}
public virtual Double discount() {
return .05;
}
}
// Extension for the Marker class
public class YellowMarker extends Marker {
public override void write() {
System.debug('Writing some text using the yellow marker.');
}
}

This code segment shows polymorphism. The example declares two objects of the same type (Marker). Even though both
objects are markers, the second object is assigned to an instance of the YellowMarker class. Hence, calling the write method
on it yields a different result than calling this method on the first object because this method has been overridden. Note that
we can call the discount method on the second object even though this method isnt part of the YellowMarker class
definition, but it is part of the extended class, and hence is available to the extending class, YellowMarker.
Marker obj1, obj2;
obj1 = new Marker();
// This outputs 'Writing some text.'
obj1.write();
obj2 = new YellowMarker();
// This outputs 'Writing some text using the yellow marker.'
obj2.write();
// We get the discount method for free
// and can call it from the YellowMarker instance.
Double d = obj2.discount();

66

Classes, Objects, and Interfaces

Extended Class Example

The extending class can have more method definitions that arent common with the original extended class. For example, the
RedMarker class below extends the Marker class and has one extra method, computePrice, that isnt available for the
Marker class. To call the extra methods, the object type must be the extending class.
// Extension for the Marker class
public class RedMarker extends Marker {
public override void write() {
System.debug('Writing some text in red.');
}
// Method only in this class
public Double computePrice() {
return 1.5;
}
}

This shows how to call the additional method on the RedMarker class.
RedMarker obj = new RedMarker();
// Call method specific to RedMarker only
Double price = obj.computePrice();

Extensions also apply to interfacesan interface can extend another interface. As with classes, when an interface extends
another interface, all the methods and properties of the extended interface are available to the extending interface.

Extended Class Example


The following is an extended example of a class, showing all the features of Apex classes. The keywords and concepts introduced
in the example are explained in more detail throughout this chapter.
// Top-level (outer) class must be public or global (usually public unless they contain
// a Web Service, then they must be global)
public class OuterClass {
// Static final variable (constant) outer class level only
private static final Integer MY_INT;
// Non-final static variable - use this to communicate state across triggers
// within a single request)
public static String sharedState;
// Static method - outer class level only
public static Integer getInt() { return MY_INT; }
// Static initialization (can be included where the variable is defined)
static {
MY_INT = 2;
}
// Member variable for outer class
private final String m;
// Instance initialization block - can be done where the variable is declared,
// or in a constructor
{
m = 'a';
}
// Because no constructor is explicitly defined in this outer class, an implicit,
// no-argument, public constructor exists

67

Classes, Objects, and Interfaces

Extended Class Example

// Inner interface
public virtual interface MyInterface {
// No access modifier is necessary for interface methods - these are always
// public or global depending on the interface visibility
void myMethod();
}
// Interface extension
interface MySecondInterface extends MyInterface {
Integer method2(Integer i);
}
// Inner class - because it is virtual it can be extended.
// This class implements an interface that, in turn, extends another interface.
// Consequently the class must implement all methods.
public virtual class InnerClass implements MySecondInterface {
// Inner member variables
private final String s;
private final String s2;
// Inner instance initialization block (this code could be located above)
{
this.s = 'x';
}
// Inline initialization (happens after the block above executes)
private final Integer i = s.length();
// Explicit no argument constructor
InnerClass() {
// This invokes another constructor that is defined later
this('none');
}
// Constructor that assigns a final variable value
public InnerClass(String s2) {
this.s2 = s2;
}
// Instance method that implements a method from MyInterface.
// Because it is declared virtual it can be overridden by a subclass.
public virtual void myMethod() { /* does nothing */ }
// Implementation of the second interface method above.
// This method references member variables (with and without the "this" prefix)
public Integer method2(Integer i) { return this.i + s.length(); }
}
// Abstract class (that subclasses the class above). No constructor is needed since
// parent class has a no-argument constructor
public abstract class AbstractChildClass extends InnerClass {
// Override the parent class method with this signature.
// Must use the override keyword
public override void myMethod() { /* do something else */ }
// Same name as parent class method, but different signature.
// This is a different method (displaying polymorphism) so it does not need
// to use the override keyword
protected void method2() {}
// Abstract method - subclasses of this class must implement this method
abstract Integer abstractMethod();
}
// Complete the abstract class by implementing its abstract method
public class ConcreteChildClass extends AbstractChildClass {

68

Classes, Objects, and Interfaces

Extended Class Example

// Here we expand the visibility of the parent method - note that visibility
// cannot be restricted by a sub-class
public override Integer abstractMethod() { return 5; }
}
// A second sub-class of the original InnerClass
public class AnotherChildClass extends InnerClass {
AnotherChildClass(String s) {
// Explicitly invoke a different super constructor than one with no arguments
super(s);
}
}
// Exception inner class
public virtual class MyException extends Exception {
// Exception class member variable
public Double d;
// Exception class constructor
MyException(Double d) {
this.d = d;
}
// Exception class method, marked as protected
protected void doIt() {}
}
// Exception classes can be abstract and implement interfaces
public abstract class MySecondException extends Exception implements MyInterface {
}
}

This code example illustrates:

A top-level class definition (also called an outer class)


Static variables and static methods in the top-level class, as well as static initialization code blocks
Member variables and methods for the top-level class
Classes with no user-defined constructor these have an implicit, no-argument constructor
An interface definition in the top-level class
An interface that extends another interface
Inner class definitions (one level deep) within a top-level class
A class that implements an interface (and, therefore, its associated sub-interface) by implementing public versions of the
method signatures
An inner class constructor definition and invocation
An inner class member variable and a reference to it using the this keyword (with no arguments)
An inner class constructor that uses the this keyword (with arguments) to invoke a different constructor
Initialization code outside of constructors both where variables are defined, as well as with anonymous blocks in curly
braces ({}). Note that these execute with every construction in the order they appear in the file, as with Java.
Class extension and an abstract class
Methods that override base class methods (which must be declared virtual)
The override keyword for methods that override subclass methods
Abstract methods and their implementation by concrete sub-classes
The protected access modifier
Exceptions as first class objects with members, methods, and constructors

69

Classes, Objects, and Interfaces

Understanding Interfaces

This example shows how the class above can be called by other Apex code:
// Construct an instance of an inner concrete class, with a user-defined constructor
OuterClass.InnerClass ic = new OuterClass.InnerClass('x');
// Call user-defined methods in the class
System.assertEquals(2, ic.method2(1));
// Define a variable with an interface data type, and assign it a value that is of
// a type that implements that interface
OuterClass.MyInterface mi = ic;
// Use instanceof and casting as usual
OuterClass.InnerClass ic2 = mi instanceof OuterClass.InnerClass ?
(OuterClass.InnerClass)mi : null;
System.assert(ic2 != null);
// Construct the outer type
OuterClass o = new OuterClass();
System.assertEquals(2, OuterClass.getInt());
// Construct instances of abstract class children
System.assertEquals(5, new OuterClass.ConcreteChildClass().abstractMethod());
// Illegal - cannot construct an abstract class
// new OuterClass.AbstractChildClass();
// Illegal cannot access a static method through an instance
// o.getInt();
// Illegal - cannot call protected method externally
// new OuterClass.ConcreteChildClass().method2();

This code example illustrates:

Construction of the outer class


Construction of an inner class and the declaration of an inner interface type
A variable declared as an interface type can be assigned an instance of a class that implements that interface
Casting an interface variable to be a class type that implements that interface (after verifying this using the instanceof
operator)

Understanding Interfaces
An interface is like a class in which none of the methods have been implementedthe method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the
declaration for that method. This way you can have different implementations of a method based on your specific application.
Defining an interface is similar to defining a new class. For example, a company might have two types of purchase orders,
ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you
needed a method to provide a discount. The amount of the discount can depend on the type of purchase order.
You can model the general concept of a purchase order as an interface and have specific implementations for customers and
employees. In the following example the focus is only on the discount aspect of a purchase order.

70

Classes, Objects, and Interfaces

Custom Iterators

This is the definition of the PurchaseOrder interface.


// An interface that defines what a purchase order looks like in general
public interface PurchaseOrder {
// All other functionality excluded
Double discount();
}

This class implements the PurchaseOrder interface for customer purchase orders.
// One implementation of the interface for customers
public class CustomerPurchaseOrder implements PurchaseOrder {
public Double discount() {
return .05; // Flat 5% discount
}
}

This class implements the PurchaseOrder interface for employee purchase orders.
// Another implementation of the interface for employees
public class EmployeePurchaseOrder implements PurchaseOrder {
public Double discount() {
return .10; // Its worth it being an employee! 10% discount
}
}

Note the following about the above example:

The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access
modifiers and contain just their signature.
The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount
method. As with Java, any class that implements an interface must define all of the methods contained in the interface.

When you define a new interface, you are defining a new data type. You can use an interface name in any place you can use
another data type name. If you define a variable whose type is an interface, any object you assign to it must be an instance of
a class that implements the interface, or a sub-interface data type.
See also Classes and Casting on page 86.
Note: You cannot add a method to a global interface after the class has been uploaded in a Managed - Released
package version.

Custom Iterators
An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for
exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. In the following example,
count is incremented by 1 every time the loop is executed (count++) :
while (count < 11) {
System.debug(count);
count++;
}

71

Classes, Objects, and Interfaces

Custom Iterators

Using the Iterator interface you can create a custom set of instructions for traversing a List through a loop. This is useful
for data that exists in sources outside of Salesforce that you would normally define the scope of using a SELECT statement.
Iterators can also be used if you have multiple SELECT statements.
Using Custom Iterators
To use custom iterators, you must create an Apex class that implements the Iterator interface.
The Iterator interface has the following instance methods:
Name

Arguments

Returns

Description

hasNext

Boolean

Returns true if there is another item in the collection


being traversed, false otherwise.

next

Any type

Returns the next item in the collection.

All methods in the Iterator interface must be declared as global or public.


You can only use a custom iterator in a while loop. For example:
IterableString x = new IterableString('This is a really cool test.');
while(x.hasNext()){
system.debug(x.next());
}

Iterators are not currently supported in for loops.


Using Custom Iterators with Iterable
If you do not want to use a custom iterator with a list, but instead want to create your own data structure, you can use the
Iterable interface to generate the data structure.
The Iterable interface has the following method:
Name

Arguments

iterator

Returns

Description

Iterator class

Returns a reference to the iterator for this interface.

The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use
to traverse the data structure.
In the following example a custom iterator iterates through a collection:
global class CustomIterable
implements Iterator<Account>{
List<Account> accs {get; set;}
Integer i {get; set;}
public CustomIterable(){
accs =
[SELECT Id, Name,
NumberOfEmployees
FROM Account
WHERE Name = 'false'];
i = 0;
}

72

Classes, Objects, and Interfaces

Keywords

global boolean hasNext(){


if(i >= accs.size()) {
return false;
} else {
return true;
}
}
global Account next(){
// 8 is an arbitrary
// constant in this example
// that represents the
// maximum size of the list.
if(i == 8){return null;}
i++;
return accs[i-1];
}
}

The following calls the above code:


global class foo implements iterable<Account>{
global Iterator<Account> Iterator(){
return new CustomIterable();
}
}

The following is a batch job that uses an iterator:


global class batchClass implements Database.batchable<Account>{
global Iterable<Account> start(Database.batchableContext info){
return new foo();
}
global void execute(Database.batchableContext info, List<Account> scope){
List<Account> accsToUpdate = new List<Account>();
for(Account a : scope){
a.Name = 'true';
a.NumberOfEmployees = 69;
accsToUpdate.add(a);
}
update accsToUpdate;
}
global void finish(Database.batchableContext info){
}
}

Keywords
Apex has the following keywords available:

final
instanceof
super
this
transient
with sharing and without sharing

73

Classes, Objects, and Interfaces

Using the final Keyword

Using the final Keyword


You can use the final keyword to modify variables.

Final variables can only be assigned a value once, either when you declare a variable or in initialization code. You must
assign a value to it in one of these two places.
Static final variables can be changed in static initialization code or where defined.
Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations.
To define a constant, mark a variable as both static and final.
Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they
are not shared across requests.
Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This
means they cannot be overridden. Use the virtual keyword if you need to override a method or class.

Using the instanceof Keyword


If you need to verify at runtime whether an object is actually an instance of a particular class, use the instanceof keyword.
The instanceof keyword can only be used to verify if the target type in the expression on the right of the keyword is a viable
alternative for the declared type of the expression on the left.
You could add the following check to the Report class in the classes and casting example before you cast the item back into
a CustomReport object.
If (Reports.get(0) instanceof CustomReport) {
// Can safely cast it back to a custom report object
CustomReport c = (CustomReport) Reports.get(0);
} Else {
// Do something with the non-custom-report.
}

Using the super Keyword


The super keyword can be used by classes that are extended from virtual or abstract classes. By using super, you can override
constructors and methods from the parent class.
For example, if you have the following virtual class:
public virtual class SuperClass {
public String mySalutation;
public String myFirstName;
public String myLastName;
public SuperClass() {
mySalutation = 'Mr.';
myFirstName = 'Carl';
myLastName = 'Vonderburg';
}
public SuperClass(String salutation, String firstName, String lastName) {
mySalutation = salutation;
myFirstName = firstName;
myLastName = lastName;
}

74

Classes, Objects, and Interfaces

Using the this Keyword

public virtual void printName() {


System.debug('My name is ' + mySalutation + myLastName);
}
public virtual String getFirstName() {
return myFirstName;
}
}

You can create the following class that extends Superclass and overrides its printName method:
public class Subclass extends Superclass {
public override void printName() {
super.printName();
System.debug('But you can call me ' + super.getFirstName());
}
}

The expected output when calling Subclass.printName is My name is Mr. Vonderburg. But you can call
me Carl.
You can also use super to call constructors. Add the following constructor to SubClass:
public Subclass() {
super('Madam', 'Brenda', 'Clapentrap');
}

Now, the expected output of Subclass.printName is My name is Madam Clapentrap. But you can call
me Brenda.
Best Practices for Using the super Keyword

Only classes that are extending from virtual or abstract classes can use super.
You can only use super in methods that are designated with the override keyword.

Using the this Keyword


There are two different ways of using the this keyword.
You can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it
appears. Use this form of the this keyword to access instance variables and methods. For example:
public class myTestThis {
string s;
{
this.s = 'TestString';
}
}

In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable
using the this keyword.

75

Classes, Objects, and Interfaces

Using the transient Keyword

Or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this
format, use the this keyword with parentheses. For example:
public class testThis {
// First constructor for the class. It requires a string parameter.
public testThis(string s2) {
}
// Second constructor for the class. It does not require a parameter.
// This constructor calls the first constructor using the this keyword.
public testThis() {
this('None');
}
}

When you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor.

Using the transient Keyword


Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view
state for a Visualforce page. For example:
Transient Integer currentTotal;

You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions,
or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that
define the types of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a
Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and
would use too many system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view
state. These objects include the following:

PageReferences
XmlStream classes
Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient,
such as a collection of Savepoints
Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
JSONParser class instances.

Static variables also don't get transmitted through the view state.
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page
causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date
continues to have its original value, which has been deserialized from the view state, so it remains the same.
<apex:page controller="ExampleController">
T1: {!t1} <br/>
T2: {!t2} <br/>
<apex:form>
<apex:commandLink value="refresh"/>

76

Classes, Objects, and Interfaces

Using the with sharing or without sharing Keywords

</apex:form>
</apex:page>
public class ExampleController {
DateTime t1;
transient DateTime t2;
public String getT1() {
if (t1 == null) t1 = System.now();
return '' + t1;
}
public String getT2() {
if (t2 == null) t2 = System.now();
return '' + t2;
}
}

See Also:
JSONParser Class

Using the with sharing or without sharing Keywords


Use the with sharing or without sharing keywords on a class to specify whether or not to enforce sharing rules.
The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class.
You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apex code
has access to all objects and fields object permissions, field-level security, sharing rules arent applied for the current user.
This is to ensure that code wont fail to run because of hidden fields or objects for a user. The only exceptions to this rule are
Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes
using the full permissions of the current user. For more information on executeAnonymous, see Anonymous Blocks on
page 186.
Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For
example:
public with sharing class sharingClass {
// Code here
}

Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not
enforced. For example:
public without sharing class noSharing {
// Code here
}

Some things to note about sharing keywords:

77

Classes, Objects, and Interfaces

Annotations

The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For
example, if a method is defined in a class declared with with sharing is called by a class declared with without
sharing, the method will execute with sharing rules enforced.
If a class isnt declared as either with or without sharing, the current sharing rules remain in effect. This means that if the
class is called by a class that has sharing enforced, then sharing is enforced for the called class.
Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained
in the class, including initialization code, constructors, and methods.
Inner classes do not inherit the sharing setting from their container class.
Classes inherit this setting from a parent class when one class extends or implements another.

Annotations
An Apex annotation modifies the way a method or class is used, similar to annotations in Java.
Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To add an annotation to a method,
specify it immediately before the method or class definition. For example:

global class MyClass {


@future
Public static void myMethod(String a)
{
//long-running Apex code
}
}

Apex supports the following annotations:

@Deprecated
@Future
@IsTest
@ReadOnly
@RemoteAction
@TestVisible

Apex REST annotations:

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut

Deprecated Annotation
Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer
be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring
code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements
continue to function for existing subscribers and API integrations.

78

Classes, Objects, and Interfaces

Future Annotation

The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums,
interfaces, or variables.
@deprecated
// This method is deprecated. Use myOptimizedMethod(String a, String b) instead.
global void myMethod(String a) {
}

Note the following rules when deprecating Apex identifiers:

Unmanaged packages cannot contain code that uses the deprecated keyword.
When an Apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be
deprecated. Any global method that uses the deprecated type in its signature, either in an input argument or the method
return type, must also be deprecated. A deprecated item, such as a method or a class, can still be referenced internally by
the package developer.
webService methods and variables cannot be deprecated.
You can deprecate an enum but you cannot deprecate individual enum values.
You can deprecate an interface but you cannot deprecate individual methods in an interface.
You can deprecate an abstract class but you cannot deprecate individual abstract methods in an abstract class.
You cannot remove the deprecated annotation to undeprecate something in Apex after you have released a package
version where that item in Apex is deprecated.

For more information about package versions, see What is a Package? on page 415.

Future Annotation
Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method
executes when Salesforce has available resources.
For example, you can use the future annotation when making an asynchronous Web service callout to an external service.
Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no
additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type. The specified parameters must
be primitive data types, arrays of primitive data types, or collections of primitive data types. Methods with the future
annotation cannot take sObjects or objects as arguments.
To make a method in a class execute asynchronously, define the method with the future annotation. For example:
global class MyFutureClass {
@future
static void myMethod(String a, Integer i) {
System.debug('Method called with: ' + a + ' and ' + i);
// Perform long-running code
}
}

Specify (callout=true) to allow callouts in a future method. Specify (callout=false) to prevent a method from making
callouts.

79

Classes, Objects, and Interfaces

IsTest Annotation

The following snippet shows how to specify that a method executes a callout:
@future (callout=true)
public static void doCalloutFromFuture() {
//Add code to perform callout
}

Future Method Considerations

Remember that any method using the future annotation requires special consideration because the method does not
necessarily execute in the same order it is called.
Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or
setMethodName methods, nor in the constructor.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call
a trigger from an annotated method that calls another annotated method.
The getContent and getContentAsPDF PageReference methods cannot be used in methods with the future
annotation.

IsTest Annotation
Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest
annotation on methods is equivalent to the testMethod keyword.
Note: Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex
code.
Classes and methods defined as isTest can be either private or public. Classes defined as isTest must be top-level
classes.
This is an example of a private test class that contains two test methods.
@isTest
private class MyTestClass {
// Methods for testing
@isTest static void test1() {
// Implement test code
}
@isTest static void test2() {
// Implement test code
}
}

This is an example of a public test class that contains utility methods for test data creation:
@isTest
public class TestUtil {
public static void createTestAccounts() {
// Create some test accounts
}
public static void createTestContacts() {
// Create some test contacts
}

80

Classes, Objects, and Interfaces

IsTest Annotation

Classes defined as isTest can't be interfaces or enums.


Methods of a public test class can only be called from a running test, that is, a test method or code invoked by a test method,
and can't be called by a non-test request.. To learn about the various ways you can run test methods, see Running Unit Test
Methods.
IsTest(SeeAllData=true) Annotation

For Apex code saved using Salesforce.com API version 24.0 and later, use the isTest(SeeAllData=true) annotation to
grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test
didnt create. Starting with Apex code saved using Salesforce.com API version 24.0, test methods dont have access by default
to pre-existing data in the organization. However, test code saved against Salesforce.com API version 23.0 and earlier continues
to have access to all data in the organization and its data access is unchanged. See Isolation of Test Data from Organization
Data in Unit Tests on page 390.
Considerations for the IsTest(SeeAllData=true) Annotation

If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test
methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method
level. However, using isTest(SeeAllData=false) on a method doesnt restrict organization data access for that
method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this
case, the method will still have access to all the data in the organization.

This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in
this class have access to all data in the organization.
// All test methods in this class can access all data.
@isTest(SeeAllData=true)
public class TestDataAccessClass {
// This test accesses an existing account.
// It also creates and accesses a new test account.
static testmethod void myTestMethod1() {
// Query an existing account in the organization.
Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1];
System.assert(a != null);
// Create a test account based on the queried account.
Account testAccount = a.clone();
testAccount.Name = 'Acme Test';
insert testAccount;
// Query the test account that was inserted.
Account testAccount2 = [SELECT Id, Name FROM Account
WHERE Name='Acme Test' LIMIT 1];
System.assert(testAccount2 != null);
}
// Like the previous method, this test method can also access all data
// because the containing class is annotated with @isTest(SeeAllData=true).
@isTest static void myTestMethod2() {
// Can access all data in the organization.
}
}

81

Classes, Objects, and Interfaces

IsTest Annotation

This second example shows how to apply the isTest(SeeAllData=true) annotation on a test method. Because the class
that the test method is contained in isnt defined with this annotation, you have to apply this annotation on the test method
to enable access to all data for that test method. The second test method doesnt have this annotation, so it can access only
the data it creates in addition to objects that are used to manage your organization, such as users.
// This class contains test methods with different data access levels.
@isTest
private class ClassWithDifferentDataAccess {
// Test method that has access to all data.
@isTest(SeeAllData=true)
static void testWithAllDataAccess() {
// Can query all data in the organization.
}
// Test method that has access to only the data it creates
// and organization setup and metadata objects.
@isTest static void testWithOwnDataAccess() {
// This method can still access the User object.
// This query returns the first user object.
User u = [SELECT UserName,Email FROM User LIMIT 1];
System.debug('UserName: ' + u.UserName);
System.debug('Email: ' + u.Email);
// Can access the test account that is created here.
Account a = new Account(Name='Test Account');
insert a;
// Access the account that was just created.
Account insertedAcct = [SELECT Id,Name FROM Account
WHERE Name='Test Account'];
System.assert(insertedAcct != null);
}
}
IsTest(OnInstall=true) Annotation

Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This
annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are
part of a test class that has this annotation, will be executed during package installation. Tests annotated to run during package
installation must pass in order for the package installation to succeed. It is no longer possible to bypass a failing test during
package installation. A test method or a class that doesn't have this annotation, or that is annotated with
isTest(OnInstall=false) or isTest, won't be executed during installation.
This example shows how to annotate a test method that will be executed during package installation. In this example, test1
will be executed but test2 and test3 won't.
public class OnInstallClass {
// Implement logic for the class.
public void method1(){
// Some code
}
}
@isTest
private class OnInstallClassTest {
// This test method will be executed
// during the installation of the package.
@isTest(OnInstall=true)
static void test1() {
// Some test code
}
// Tests excluded from running during the

82

Classes, Objects, and Interfaces

ReadOnly Annotation

// the installation of a package.


@isTest
static void test2() {
// Some test code
}
static testmethod void test3() {
// Some test code
}
}

ReadOnly Annotation
The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database. All other limits still
apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks
you from performing the following operations within the request: DML operations, calls to System.schedule, calls to
methods annotated with @future, and sending emails.
The @ReadOnly annotation is available for Web services and the Schedulable interface. To use the @ReadOnly annotation,
the top level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page calls
a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top level request, not the
Web service.
Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods will run with the same
relaxed restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration
component like <apex:pageBlockTable>, you can set the readonly attribute on the <apex:page> tag to true. For
more information, see Working with Large Sets of Data in the Visualforce Developer's Guide.

RemoteAction Annotation
The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This
process is often referred to as JavaScript remoting.
Note: Methods with the RemoteAction annotation must be static and either global or public.

To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);

namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if

the class comes from an installed package.


controller is the name of your Apex controller.
method is the name of the Apex method youre calling.
parameters is the comma-separated list of parameters that your method takes.
callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can
also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as
parameters.

83

Classes, Objects, and Interfaces

TestVisible Annotation

configuration configures the handling of the remote call and response. Use this to change the behavior of a remoting

call, such as whether or not to escape the Apex methods response.


In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
@RemoteAction
global static String getItemId(String objectName) { ... }

Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces
as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have
an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes
and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference.
For more information, see JavaScript Remoting for Apex Controllers in the Visualforce Developer's Guide.

TestVisible Annotation
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the
test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive
access level for running tests only. This annotation doesnt change the visibility of members if accessed by non-test classes.
With this annotation, you dont have to change the access modifiers of your methods and member variables to public if you
want to access them in a test method. For example, if a private member variable isnt supposed to be exposed to external classes
but it should be accessible by a test method, you can add the TestVisible annotation to the variable definition.
This example shows how to annotate a private class member variable and private method with TestVisible.
public class TestVisibleExample {
// Private member variable
@TestVisible private static Integer recordNumber = 1;
// Private method
@TestVisible private static void updateRecord(String name) {
// Do something
}
}

This is the test class that uses the previous class. It contains the test method that accesses the annotated member variable and
method.
@isTest
private class TestVisibleExampleTest {
@isTest static void test1() {
// Access private variable annotated with TestVisible
Integer i = TestVisibleExample.recordNumber;
System.assertEquals(1, i);
// Access private method annotated with TestVisible
TestVisibleExample.updateRecord('RecordName');
// Perform some verification
}
}

Apex REST Annotations


Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service.

84

Classes, Objects, and Interfaces

Apex REST Annotations

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut

RestResource Annotation
The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
These are some considerations when using this annotation:

The URL mapping is relative to https://instance.salesforce.com/services/apexrest/.


A wildcard character (*) may be used.
The URL mapping is case-sensitive. A URL mapping for my_url will only match a REST resource containing my_url
and not My_Url.
To use this annotation, your Apex class must be defined as global.

URL Guidelines
URL path mappings are as follows:

The path must begin with a '/'


If an '*' appears, it must be preceded by '/' and followed by '/', unless the '*' is the last character, in which case it need not
be followed by '/'

The rules for mapping URLs are:

An exact match always wins.


If no exact match is found, find all the patterns with wildcards that match, and then select the longest (by string length)
of those.
If no wildcard match is found, an HTTP response status code 404 is returned.

The URL for a namespaced classes contains the namespace. For example, if your class is in namespace abc and the class is
mapped to your_url, then the API URL is modified as follows:
https://instance.salesforce.com/services/apexrest/abc/your_url/. In the case of a URL collision, the
namespaced class is always used.

HttpDelete Annotation
The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP DELETE request is sent, and deletes the specified resource.
To use this annotation, your Apex method must be defined as global static.

HttpGet Annotation
The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP GET request is sent, and returns the specified resource.
These are some considerations when using this annotation:

To use this annotation, your Apex method must be defined as global static.
Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method.

85

Classes, Objects, and Interfaces

Classes and Casting

HttpPatch Annotation
The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP PATCH request is sent, and updates the specified resource.
To use this annotation, your Apex method must be defined as global static.

HttpPost Annotation
The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP POST request is sent, and creates a new resource.
To use this annotation, your Apex method must be defined as global static.

HttpPut Annotation
The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP PUT request is sent, and creates or updates the specified resource.
To use this annotation, your Apex method must be defined as global static.

Classes and Casting


In general, all type information is available at runtime. This means that Apex enables casting, that is, a data type of one class
can be assigned to a data type of another class, but only if one class is a child of the other class. Use casting when you want to
convert an object from one data type to another.
In the following example, CustomReport extends the class Report. Therefore, it is a child of that class. This means that
you can use casting to assign objects with the parent data type (Report) to the objects of the child data type (CustomReport).
In the following code block, first, a custom report object is added to a list of report objects. After that, the custom report object
is returned as a report object, then is cast back into a custom report object.
Public virtual class Report {
Public class CustomReport extends Report {
// Create a list of report objects
Report[] Reports = new Report[5];
// Create a custom report object
CustomReport a = new CustomReport();
// Because the custom report is a sub class of the Report class,
// you can add the custom report object a to the list of report objects
Reports.add(a);
//
//
//
//

The following is not legal, because the compiler does not know that what you are
returning is a custom report. You must use cast to tell it that you know what
type you are returning
CustomReport c = Reports.get(0);

// Instead, get the first item in the list by casting it back to a custom report object
CustomReport c = (CustomReport) Reports.get(0);
}
}

86

Classes, Objects, and Interfaces

Classes and Collections

Figure 4: Casting Example


In addition, an interface type can be cast to a sub-interface or a class type that implements that interface.
Tip: To verify if a class is a specific type of class, use the instanceOf keyword. For more information, see Using
the instanceof Keyword on page 74.

Classes and Collections


Lists and maps can be used with classes and interfaces, in the same ways that lists and maps can be used with sObjects. This
means, for example, that you can use a user-defined data type only for the value of a map, not for the key. Likewise, you cannot
create a set of user-defined objects.
If you create a map or list of interfaces, any child type of the interface can be put into that collection. For instance, if the List
contains an interface i1, and MyC implements i1, then MyC can be placed in the list.

Collection Casting
Because collections in Apex have a declared type at runtime, Apex allows collection casting.

87

Classes, Objects, and Interfaces

Differences Between Apex Classes and Java Classes

Collections can be cast in a similar manner that arrays can be cast in Java. For example, a list of CustomerPurchaseOrder
objects can be assigned to a list of PurchaseOrder objects if class CustomerPurchaseOrder is a child of class PurchaseOrder.
public virtual class PurchaseOrder {
Public class CustomerPurchaseOrder extends PurchaseOrder {
}
{
List<PurchaseOrder> POs = new PurchaseOrder[] {};
List<CustomerPurchaseOrder> CPOs = new CustomerPurchaseOrder[]{};
POs = CPOs;}
}

Once the CustomerPurchaseOrder list is assigned to the PurchaseOrder list variable, it can be cast back to a list of
CustomerPurchaseOrder objects, but only because that instance was originally instantiated as a list of CustomerPurchaseOrder.
A list of PurchaseOrder objects that is instantiated as such cannot be cast to a list of CustomerPurchaseOrder objects, even if
the list of PurchaseOrder objects contains only CustomerPurchaseOrder objects.
If the user of a PurchaseOrder list that only includes CustomerPurchaseOrders objects tries to insert a
non-CustomerPurchaseOrder subclass of PurchaseOrder (such as InternalPurchaseOrder), a runtime exception results.
This is because Apex collections have a declared type at runtime.
Note: Maps behave in the same way as lists with regards to the value side of the Mapif the value side of map A
can be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime
error results if the casting is not valid with the particular map at runtime.

Differences Between Apex Classes and Java Classes


The following is a list of the major differences between Apex classes and Java classes:

Inner classes and interfaces can only be declared one level deep inside an outer class.
Static methods and variables can only be declared in a top-level class definition, not in an inner class.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this
keyword).
The private access modifier is the default, and means that the method or variable is accessible only within the Apex
class in which it is defined. If you do not specify an access modifier, the method or variable is private.
Specifying no access modifier for a method or variable and the private access modifier are synonymous.
The public access modifier means the method or variable can be used by any Apex in this application or namespace.
The global access modifier means the method or variable can be used by any Apex code that has access to the class, not
just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced
outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global,
you must also declare the class that contains it as global.
Methods and classes are final by default.
The virtual definition modifier allows extension and overrides.
The override keyword must be used explicitly on methods that override base class methods.

Interface methods have no modifiersthey are always global.


Exception classes must extend either exception or another user-defined exception.
Their names must end with the word exception.

88

Classes, Objects, and Interfaces

Class Definition Creation

Exception classes have four implicit constructors that are built-in, although you can add others.

Classes and interfaces can be defined in triggers and anonymous blocks, but only as local.

See Also:
Exceptions in Apex

Class Definition Creation


To create a class in Salesforce:
1. From Setup, click Develop > Apex Classes.
2. Click New.
3. Click Version Settings to specify the version of Apex and the API used with this class. If your organization has installed
managed packages from the AppExchange, you can also specify which version of each managed package to use with this
class. Use the default values for all versions. This associates the class with the most recent version of Apex and the API,
as well as each managed package. You can specify an older version of a managed package if you want to access components
or functionality that differs from the most recent package version. You can specify an older version of Apex and the API
to maintain specific behavior.
4. In the class editor, enter the Apex code for the class. A single class can be up to 1 million characters in length, not including
comments, test methods, or classes defined using @isTest.
5. Click Save to save your changes and return to the class detail screen, or click Quick Save to save your changes and continue
editing your class. Your Apex class must compile correctly before you can save your class.
Classes can also be automatically generated from a WSDL by clicking Generate from WSDL. See SOAP Services: Defining
a Class from a WSDL Document on page 312.
Once saved, classes can be invoked through class methods or variables by other Apex code, such as a trigger.
Note: To aid backwards-compatibility, classes are stored with the version settings for a specified version of Apex
and the API. If the Apex class references components, such as a custom object, in installed managed packages, the
version settings for each managed package referenced by the class is saved too. Additionally, classes are stored with
an isValid flag that is set to true as long as dependent metadata has not changed since the class was last compiled.
If any changes are made to object names or fields that are used in the class, including superficial changes such as edits
to an object or field description, or if changes are made to a class that calls this class, the isValid flag is set to false.
When a trigger or Web service call invokes the class, the code is recompiled and the user is notified if there are any
errors. If there are no errors, the isValid flag is reset to true.

The Apex Class Editor


When editing Visualforce or Apex, either in the Visualforce development mode footer or from Setup, an editor is available
with the following functionality:
Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.
Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.
To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
89

Classes, Objects, and Interfaces

Naming Conventions

To make the search operation case sensitive, select the Match Case option.
To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag
with an <h2> tag and keep all the attributes on the original <h1> intact, search for <h1(\s+)(.*)> and replace it
with <h2$1$2>.

Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Undo (

) and Redo (

Use undo to reverse an editing action and redo to recreate an editing action that was undone.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used
with go to line (

) to quickly navigate through the editor.

Line and character count


The total number of lines and characters is displayed in the status bar at the bottom of the editor.

Naming Conventions
We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase
verb, and variable names should be meaningful.
It is not legal to define a class and interface with the same name in the same class. It is also not legal for an inner class to have
the same name as its outer class. However, methods and variables have their own namespaces within the class so these three
types of names do not clash with each other. In particular it is legal for a variable, method, and a class within a class to have
the same name.

Name Shadowing
Member variables can be shadowed by local variablesin particular function arguments. This allows methods and constructors
of the standard Java form:
Public Class Shadow {
String s;
Shadow(String s) { this.s = s; } // Same name ok
setS(String s) { this.s = s; } // Same name ok
}

Member variables in one class can shadow member variables with the same name in a parent classes. This can be useful if the
two classes are in different top-level classes and written by different teams. For example, if one has a reference to a class C and

90

Classes, Objects, and Interfaces

Namespace Prefix

wants to gain access to a member variable M in parent class P (with the same name as a member variable in C) the reference
should be assigned to a reference to P first.
Static variables can be shadowed across the class hierarchyso if P defines a static S, a subclass C can also declare a static S.
References to S inside C refer to that staticin order to reference the one in P, the syntax P.S must be used.
Static class variables cannot be referenced through a class instance. They must be referenced using the raw variable name by
itself (inside that top-level class file) or prefixed with the class name. For example:
public class p1 {
public static final Integer CLASS_INT = 1;
public class c { };
}
p1.c c = new p1.c();
// This is illegal
// Integer i = c.CLASS_INT;
// This is correct
Integer i = p1.CLASS_INT;

Namespace Prefix
The Salesforce application supports the use of namespace prefixes. Namespace prefixes are used in managed Force.com
AppExchange packages to differentiate custom object and field names from those in use by other organizations. After a
developer registers a globally unique namespace prefix and registers it with AppExchange registry, external references to custom
object and field names in the developer's managed packages take on the following long format:
namespace_prefix__obj_or_field_name__c

Because these fully-qualified names can be onerous to update in working SOQL statements, SOSL statements, and Apex
once a class is marked as managed, Apex supports a default namespace for schema names. When looking at identifiers, the
parser considers the namespace of the current object and then assumes that it is the namespace of all other objects and fields
unless otherwise specified. Consequently, a stored class should refer to custom object and field names directly (using
obj_or_field_name__c) for those objects that are defined within its same application namespace.
Tip: Only use namespace prefixes when referring to custom objects and fields in managed packages that have been
installed to your organization from theAppExchange.

Using Namespaces When Invoking Package Methods


To invoke a method that is defined in a managed package, Apex allows fully-qualified identifiers of the form:
namespace_prefix.class.method(args)

Using the System Namespace


The System namespace is the default namespace in Apex. This means that you can omit the namespace when creating a new
instance of a system class or when calling a system method. For example, because the built-in URL class is in the System
namespace, both of these statements to create an instance of the URL class are equivalent:
System.URL url1 = new System.URL('http://na1.salesforce.com');

91

Classes, Objects, and Interfaces

Namespace, Class, and Variable Name Precedence

And:
URL url1 = new URL('http://na1.salesforce.com');

Similarly, to call a static method on the URL class, you can write either of the following:
System.URL.getCurrentRequestUrl();

Or:
URL.getCurrentRequestUrl();

Note: In addition to the System namespace, there is a built-in System class in the System namespace, which
provides methods like assertEquals and debug. Dont get confused by the fact that both the namespace and the
class have the same name in this case. The System.debug('debug message'); and
System.System.debug('debug message'); statements are equivalent.
Using the System Namespace for Disambiguation
It is easier to not include the System namespace when calling static methods of system classes, but there are situations where
you must include the System namespace to differentiate the built-in Apex classes from custom Apex classes with the same
name. If your organization contains Apex classes that youve defined with the same name as a built-in class, the Apex runtime
defaults to your custom class and calls the methods in your class. Lets take a look at the following example.
Create this custom Apex class:
public class Database {
public static String query() {
return 'wherefore art thou namespace?';
}
}

Execute this statement in the Developer Console:


sObject[] acct = Database.query('SELECT Name FROM Account LIMIT 1);
System.debug(acct[0].get('Name'));

When the Database.query statement executes, Apex looks up the query method on the custom Database class first.
However, the query method in this class doesnt take any parameters and no match is found, hence you get an error. The
custom Database class overrides the built-in Database class in the System namespace. To solve this problem, add the
System namespace prefix to the class name to explicitly instruct the Apex runtime to call the query method on the built-in
Database class in the System namespace:
sObject[] acct = System.Database.query('SELECT Name FROM Account LIMIT 1);
System.debug(acct[0].get('Name'));

Namespace, Class, and Variable Name Precedence


Because local variables, class names, and namespaces can all hypothetically use the same identifiers, the Apex parser evaluates
expressions in the form of name1.name2.[...].nameN as follows:
1. The parser first assumes that name1 is a local variable with name2 - nameN as field references.
92

Classes, Objects, and Interfaces

Type Resolution and System Namespace for Types

2. If the first assumption does not hold true, the parser then assumes that name1 is a class name and name2 is a static variable
name with name3 - nameN as field references.
3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, and name4 - nameN are field references.
4. If the third assumption does not hold true, the parser reports an error.
If the expression ends with a set of parentheses (for example, name1.name2.[...].nameM.nameN()), the Apex parser
evaluates the expression as follows:
1. The parser first assumes that name1 is a local variable with name2 - nameM as field references, and nameN as a method
invocation.
2. If the first assumption does not hold true:

If the expression contains only two identifiers (name1.name2()), the parser then assumes that name1 is a class name
and name2 is a method invocation.
If the expression contains more than two identifiers, the parser then assumes that name1 is a class name, name2 is a
static variable name with name3 - nameM as field references, and nameN is a method invocation.

3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, name4 - nameM are field references, and nameN is a method invocation.
4. If the third assumption does not hold true, the parser reports an error.
However, with class variables Apex also uses dot notation to reference member variables. Those member variables might refer
to other class instances, or they might refer to an sObject which has its own dot notation rules to refer to field names (possibly
navigating foreign keys).
Once you enter an sObject field in the expression, the remainder of the expression stays within the sObject domain, that is,
sObject fields cannot refer back to Apex expressions.
For instance, if you have the following class:
public class c {
c1 c1 = new c1();
class c1 { c2 c2; }
class c2 { Account a; }
}

Then the following expressions are all legal:


c.c1.c2.a.name
c.c1.c2.a.owner.lastName.toLowerCase()
c.c1.c2.a.tasks
c.c1.c2.a.contacts.size()

Type Resolution and System Namespace for Types


Because the type system must resolve user-defined types defined locally or in other classes, the Apex parser evaluates types as
follows:
1.
2.
3.
4.

For a type reference TypeN, the parser first looks up that type as a scalar type.
If TypeN is not found, the parser looks up locally defined types.
If TypeN still is not found, the parser looks up a class of that name.
If TypeN still is not found, the parser looks up system types such as sObjects.

93

Classes, Objects, and Interfaces

Apex Code Versions

For the type T1.T2 this could mean an inner type T2 in a top-level class T1, or it could mean a top-level class T2 in the
namespace T1 (in that order of precedence).

Apex Code Versions


To aid backwards-compatibility, classes and triggers are stored with the version settings for a specific Salesforce.com API
version. If an Apex class or trigger references components, such as a custom object, in installed managed packages, the version
settings for each managed package referenced by the class are saved too. This ensures that as Apex, the API, and the components
in managed packages evolve in subsequent released versions, a class or trigger is still bound to versions with specific, known
behavior.
Setting a version for an installed package determines the exposed interface and behavior of any Apex code in the installed
package. This allows you to continue to reference Apex that may be deprecated in the latest version of an installed package,
if you installed a version of the package before the code was deprecated.
Typically, you reference the latest Salesforce.com API version and each installed package version. If you save an Apex class or
trigger without specifying the Salesforce.com API version, the class or trigger is associated with the latest installed version by
default. If you save an Apex class or trigger that references a managed package without specifying a version of the managed
package, the class or trigger is associated with the latest installed version of the managed package by default.

Setting the Salesforce API Version for Classes and Triggers


To set the Salesforce.com API and Apex version for a class or trigger:
1. Edit either a class or trigger, and click Version Settings.
2. Select the Version of the Salesforce.com API. This is also the version of Apex associated with the class or trigger.
3. Click Save.
If you pass an object as a parameter in a method call from one Apex class, C1, to another class, C2, and C2 has different fields
exposed due to the Salesforce.com API version setting, the fields in the objects are controlled by the version settings of C2.
Using the following example, the Categories field is set to null after calling the insertIdea method in class C2 from
a method in the test class C1, because the Categories field is not available in version 13.0 of the API.
The first class is saved using Salesforce.com API version 13.0:
// This class is saved using Salesforce API version 13.0
// Version 13.0 does not include the Idea.categories field
global class C2
{
global Idea insertIdea(Idea a) {
insert a; // category field set to null on insert
// retrieve the new idea
Idea insertedIdea = [SELECT title FROM Idea WHERE Id =:a.Id];
return insertedIdea;
}
}

The following class is saved using Salesforce.com API version 16.0:


@isTest
// This class is bound to API version 16.0 by Version Settings
private class C1
{
static testMethod void testC2Method() {

94

Classes, Objects, and Interfaces

Setting Package Versions for Apex Classes and Triggers

Idea i = new Idea();


i.CommunityId = '09aD000000004YCIAY';
i.Title = 'Testing Version Settings';
i.Body = 'Categories field is included in API version 16.0';
i.Categories = 'test';
C2 c2 = new C2();
Idea returnedIdea = c2.insertIdea(i);
// retrieve the new idea
Idea ideaMoreFields = [SELECT title, categories FROM Idea
WHERE Id = :returnedIdea.Id];
// assert that the categories field from the object created
// in this class is not null
System.assert(i.Categories != null);
// assert that the categories field created in C2 is null
System.assert(ideaMoreFields.Categories == null);
}
}

Setting Package Versions for Apex Classes and Triggers


To configure the package version settings for a class or trigger:
1. Edit either a class or trigger, and click Version Settings.
2. Select a Version for each managed package referenced by the class or trigger. This version of the managed package will
continue to be used by the class or trigger if later versions of the managed package are installed, unless you manually update
the version setting. To add an installed managed package to the settings list, select a package from the list of available
packages. The list is only displayed if you have an installed managed package that is not already associated with the class
or trigger.
3. Click Save.
Note the following when working with package version settings:

If you save an Apex class or trigger that references a managed package without specifying a version of the managed package,
the Apex class or trigger is associated with the latest installed version of the managed package by default.
You cannot Remove a class or trigger's version setting for a managed package if the package is referenced in the class or
trigger. Use Show Dependencies to find where a managed package is referenced by a class or trigger.

Lists of Custom Types and Sorting


Lists can hold objects of your user-defined types (your Apex classes). Lists of user-defined types can be sorted.
To sort such a list using the List.sort method, your Apex classes must implement the Comparable interface.
The sort criteria and sort order depends on the implementation that you provide for the compareTo method of the Comparable
interface. For more information on implementing the Comparable interface for your own classes, see the Comparable
Interface.

Using Custom Types in Map Keys and Sets


You can add instances of your own Apex classes to maps and sets.
For maps, instances of your Apex classes can be added either as keys or values, but if you add them as keys, there are some
special rules that your class must implement for the map to function correctly, that is, for the key to fetch the right value.
Similarly, if set elements are instances of your custom class, your class must follow those same rules.

95

Classes, Objects, and Interfaces

Using Custom Types in Map Keys and Sets

Warning: If the object in your map keys or set elements changes after being added to the collection, it wont be found
anymore because of changed field values.
When using a custom type (your Apex class) for the map key or set elements, provide equals and hashCode methods in
your class. Apex uses these two methods to determine equality and uniqueness of keys for your objects.

Adding equals and hashCode Methods to Your Class


To ensure that map keys of your custom type are compared correctly and their uniqueness can be determined consistently,
provide an implementation of the following two methods in your class:

The equals method with this signature:


public Boolean equals(Object obj) {
// Your implementation
}

Keep in mind the following when implementing the equals method. Assuming x, y, and z are non-null instances of your
class, the equals method must be:

Reflexive: x.equals(x)
Symmetric: x.equals(y) should return true if and only if y.equals(x) returns true
Transitive: if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
Consistent: multiple invocations of x.equals(y) consistently return true or consistently return false
For any non-null reference value x, x.equals(null) should return false

The equals method in Apex is based on the equals method in Java.

The hashCode method with this signature:


public Integer hashCode() {
// Your implementation
}

Keep in mind the following when implementing the hashCode method.


If the hashCode method is invoked on the same object more than once during execution of an Apex request, it must
return the same value.
If two objects are equal, based on the equals method, hashCode must return the same value.
If two objects are unequal, based on the result of the equals method, it is not required that hashCode return distinct
values.
The hashCode method in Apex is based on the hashCode method in Java.
Another benefit of providing the equals method in your class is that it simplifies comparing your objects. You will be able
to use the == operator to compare objects, or the equals method. For example:
// obj1 and obj2 are instances of MyClass
if (obj1 == obj2) {
// Do something
}
if (obj1.equals(obj2)) {
// Do something
}

96

Classes, Objects, and Interfaces

Using Custom Types in Map Keys and Sets

Sample
This sample shows how to implement the equals and hashCode methods. The class that provides those methods is listed
first. It also contains a constructor that takes two Integers. The second example is a code snippet that creates three objects of
the class, two of which have the same values. Next, map entries are added using the pair objects as keys. The sample verifies
that the map has only two entries since the entry that was added last has the same key as the first entry, and hence, overwrote
it. The sample then uses the == operator, which works as expected because the class implements equals. Also, some additional
map operations are performed, like checking whether the map contains certain keys, and writing all keys and values to the
debug log. Finally, the sample creates a set and adds the same objects to it. It verifies that the set size is two, since only two
objects out of the three are unique.
public class PairNumbers {
Integer x,y;
public PairNumbers(Integer a, Integer b) {
x=a;
y=b;
}
public Boolean equals(Object obj) {
if (obj instanceof PairNumbers) {
PairNumbers p = (PairNumbers)obj;
return ((x==p.x) && (y==p.y));
}
return false;
}
public Integer hashCode() {
return (31 * x) ^ y;
}
}

This code snippet makes use of the PairNumbers class.


Map<PairNumbers, String> m = new Map<PairNumbers, String>();
PairNumbers p1 = new PairNumbers(1,2);
PairNumbers p2 = new PairNumbers(3,4);
// Duplicate key
PairNumbers p3 = new PairNumbers(1,2);
m.put(p1, 'first');
m.put(p2, 'second');
m.put(p3, 'third');
// Map size is 2 because the entry with
// the duplicate key overwrote the first entry.
System.assertEquals(2, m.size());
// Use the == operator
if (p1 == p3) {
System.debug('p1 and p3 are equal.');
}
// Perform some other operations
System.assertEquals(true, m.containsKey(p1));
System.assertEquals(true, m.containsKey(p2));
System.assertEquals(false, m.containsKey(new PairNumbers(5,6)));
for(PairNumbers pn : m.keySet()) {
System.debug('Key: ' + pn);
}
List<String> mValues = m.values();
System.debug('m.values: ' + mValues);
// Create a set

97

Classes, Objects, and Interfaces

Using Custom Types in Map Keys and Sets

Set<PairNumbers> s1 = new Set<PairNumbers>();


s1.add(p1);
s1.add(p2);
s1.add(p3);
// Verify that we have only two elements
// since the p3 is equal to p1.
System.assertEquals(2, s1.size());

98

Chapter 7
Working with Data in Apex
In this chapter ...

sObject Types
Adding and Retrieving Data
DML
SOQL and SOSL Queries
SOQL For Loops
sObject Collections
Dynamic Apex
Apex Security and Sharing
Custom Settings

This chapter describes how you can add and interact with data in the Force.com
platform persistence layer. In this chapter, youll learn about the main data type
that holds data objectsthe sObject data type. Youll also learn about the
language used to manipulate dataData Manipulation Language (DML), and
query languages used to retrieve data, such as the (), among other things. This
chapter also explains the use of custom settings in Apex.

99

Working with Data in Apex

sObject Types

sObject Types
In this developer's guide, the term sObject refers to any object that can be stored in the Force.com platform database. An
sObject variable represents a row of data and can only be declared in Apex using the SOAP API name of the object. For
example:
Account a = new Account();
MyCustomObject__c co = new MyCustomObject__c();

Similar to the SOAP API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data
type can be used in code that processes different types of sObjects.
The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example:
sObject s = new Account();

You can also use casting between the generic sObject type and the specific sObject type. For example:
// Cast the generic variable s from the example above
// into a specific account and account variable a
Account a = (Account)s;
// The following generates a runtime error
Contact c = (Contact)s;

Because sObjects work like objects, you can also have the following:
Object obj = s;
// and
a = (Account)obj;

DML operations work on variables declared as the generic sObject data type as well as with regular sObjects.
sObject variables are initialized to null, but can be assigned a valid object reference with the new operator. For example:
Account a = new Account();

Developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sObject.
For example:
Account a = new Account(name = 'Acme', billingcity = 'San Francisco');

For information on accessing existing sObjects from the Force.com platform database, see SOQL and SOSL Queries in
the Force.com SOQL and SOSL Reference.
Note: The ID of an sObject is a read-only value and can never be modified explicitly in Apex unless it is cleared
during a clone operation, or is assigned with a constructor. The Force.com platform assigns ID values automatically
when an object record is initially inserted to the database for the first time. For more information see Lists on page
29.

100

Working with Data in Apex

Accessing sObject Fields

Custom Labels
Custom labels are not standard sObjects. You cannot create a new instance of a custom label. You can only access the value
of a custom label using system.label.label_name. For example:
String errorMsg = System.Label.generic_error;

For more information on custom labels, see Custom Labels Overview in the Salesforce online help.

Accessing sObject Fields


As in Java, sObject fields can be accessed or changed with simple dot notation. For example:
Account a = new Account();
a.Name = 'Acme';
// Access the account name field and assign it 'Acme'

System generated fields, such as Created By or Last Modified Date, cannot be modified. If you try, the Apex runtime
engine generates an error. Additionally, formula field values and values for other fields that are read-only for the context user
cannot be changed.
If you use the generic sObject type instead of a specific object, such as Account, you can retrieve only the Id field using dot
notation. You can set the Id field for Apex code saved using Salesforce.com API version 27.0 and later). Alternatively, you
can use the generic sObject put and get methods. See sObject Class.
This example shows how you can access the Id field and operations that arent allowed on generic sObjects.
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
// This is allowed
ID id = s.Id;
// The following line results in an error when you try to save
String x = s.Name;
// This line results in an error when you try to save using API version 26.0 or earlier
s.Id = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1].Id;

Note: If your organization has enabled person accounts, you have two different kinds of accounts: business accounts
and person accounts. If your code creates a new account using name, a business account is created. If your code uses
LastName, a person account is created.
If you want to perform operations on an sObject, it is recommended that you first convert it into a specific object. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
ID id = s.ID;
Account convertedAccount = (Account)s;
convertedAccount.name = 'Acme2';
update convertedAccount;
Contact sal = new Contact(FirstName = 'Sal', Account = convertedAccount);

The following example shows how you can use SOSL over a set of records to determine their object types. Once you have
converted the generic sObject record into a Contact, Lead, or Account, you can modify its fields accordingly:
public class convertToCLA {
List<Contact> contacts;

101

Working with Data in Apex

Validating sObjects and Fields

List<Lead> leads;
List<Account> accounts;
public void convertType(Integer phoneNumber) {
List<List<sObject>> results = [FIND '4155557000'
IN Phone FIELDS
RETURNING Contact(Id, Phone, FirstName, LastName),
Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)];
sObject[] records = ((List<sObject>)results[0]);
if (!records.isEmpty()) {
for (Integer i = 0; i < records.size(); i++) {
sObject record = records[i];
if (record.getSObjectType() == Contact.sObjectType) {
contacts.add((Contact) record);
} else if (record.getSObjectType() == Lead.sObjectType){
leads.add((Lead) record);
} else if (record.getSObjectType() == Account.sObjectType) {
accounts.add((Account) record);
}
}
}
}
}

Validating sObjects and Fields


When Apex code is parsed and validated, all sObject and field references are validated against actual object and field names,
and a parse-time exception is thrown when an invalid name is used.
In addition, the Apex parser tracks the custom objects and fields that are used, both in the code's syntax as well as in embedded
SOQL and SOSL statements. The platform prevents users from making the following types of modifications when those
changes cause Apex code to become invalid:

Changing a field or object name


Converting from one data type to another
Deleting a field or object
Making certain organization-wide changes, such as record sharing, field history tracking, or record types

Adding and Retrieving Data


Apex is tightly integrated with the Force.com platform persistence layer. Records in the database can be inserted and manipulated
through Apex directly using simple statements. The language in Apex that allows you to add and manage records in the
database is the Data Manipulation Language (DML). In contrast to the SOQL language, which is used for read
operationsquerying records, DML is used for write operations.
Before inserting or manipulating records, record data is created in memory as sObjects. The sObject data type is a generic
data type and corresponds to the data type of the variable that will hold the record data. There are specific data types, subtyped
from the sObject data type, which correspond to data types of standard object records, such as Account or Contact, and custom
objects, such as Invoice_Statement__c. Typically, you will work with these specific sObject data types. But sometimes, when
you dont know the type of the sObject in advance, you can work with the generic sObject data type. This is an example of
how you can create a new specific Account sObject and assign it to a variable.
Account a = new Account(Name='Account Example');

102

Working with Data in Apex

DML

In the previous example, the account referenced by the variable a exists in memory with the required Name field. However, it
is not persisted yet to the Force.com platform persistence layer. You need to call DML statements to persist sObjects to the
database. Here is an example of creating and persisting this account using the insert statement.
Account a = new Account(Name='Account Example');
insert a;

Also, you can use DML to modify records that have already been inserted. Among the operations you can perform are record
updates, deletions, restoring records from the Recycle Bin, merging records, or converting leads. After querying for records,
you get sObject instances that you can modify and then persist the changes of. This is an example of querying for an existing
record that has been previously persisted, updating a couple of fields on the sObject representation of this record in memory,
and then persisting this change to the database.
// Query existing account.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account Example' LIMIT 1];
// Write the old values the debug log before updating them.
System.debug('Account Name before update: ' + a.Name); // Name is Account Example
System.debug('Account Industry before update: ' + a.Industry);// Industry is not set
// Modify the two fields on the sObject.
a.Name = 'Account of the Day';
a.Industry = 'Technology';
// Persist the changes.
update a;
// Get a new copy of the account from the database with the two fields.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account of the Day' LIMIT 1];
// Verify that updated field values were persisted.
System.assertEquals('Account of the Day', a.Name);
System.assertEquals('Technology', a.Industry);

DML
DML Statements vs. Database Class Methods
Apex offers two ways to perform DML operations: using DML statements or Database class methods. This provides flexibility
in how you perform data operations. DML statements are more straightforward to use and result in exceptions that you can
handle in your code. This is an example of a DML statement to insert a new record.
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
insert acctList;

103

Working with Data in Apex

DML Operations As Atomic Transactions

This is an equivalent example to the previous one but it uses a method of the Database class instead of the DML verb.
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
Database.SaveResult[] sr = Database.insert(acctList, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully inserted account. Account ID: ' + sr.getId());
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}

One difference between the two options is that by using the Database class method, you can specify whether or not to allow
for partial record processing if errors are encountered. You can do so by passing an additional second Boolean parameter. If
you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead
of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of
each operation and any errors encountered. By default, this optional parameter is true, which means that if at least one
sObject cant be processed, all remaining sObjects wont and an exception will be thrown for the record that causes a failure.
The following helps you decide when you want to use DML statements or Database class methods.

Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception
that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions
are handled in most database procedural languages.
Use Database class methods if you want to allow partial success of a bulk DML operationif a record fails, the remainder
of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the
operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use
the appropriate results array to judge success or failure. Note that Database methods also include a syntax that supports
thrown exceptions, similar to DML statements.
Note:
Most operations overlap between the two, except for a few.

The convertLead operation is only available as a Database class method, not as a DML statement.
The Database class also provides methods not available as DML statements, such as methods transaction control
and rollback, emptying the Recycle Bin, and methods related to SOQL queries.

DML Operations As Atomic Transactions


DML operations execute within a transaction. All DML operations in a transaction either complete successfully, or if an error
occurs in one operation, the entire transaction is rolled back and no data is committed to the database. The boundary of a
transaction can be a trigger, a class method, an anonymous block of code, an Apex page, or a custom Web service method.

104

Working with Data in Apex

How DML Works

All operations that occur inside the transaction boundary represent a single unit of operations. This also applies to calls that
are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running
in the transaction boundary. For example, consider the following chain of operations: a custom Apex Web service method
calls a method in a class that performs some DML operations. In this case, all changes are committed to the database only<