text
stringlengths
73
5.28k
apex developer guide version 58.0, summer ’23 @salesforcedocs last updated: june 15, 2023© copyright 2000–2023 salesforce, inc. all rights reserved. salesforce is a registered trademark of salesforce, inc., as are other names and marks. other marks appearing herein may be trademarks of their respective owners.contents apex developer guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 release notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 getting started with apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 introducing apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 apex development process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 apex quick start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 writing apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 data types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 control flow statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 classes, objects, and interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 working with data in apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 running apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 invoking apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 apex transactions and governor limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 using salesforce features with apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 integration and apex utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 debugging, testing, and deploying apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 debugging apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 testing apex . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634 deploying apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 distributing apex using managed packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675 apex reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 shipping invoice example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 reserved keywords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 documentation typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694apex developer guide apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the salesforce platform server, in conjunction with calls to the api. this guide introduces you to the apex development process and provides valuable information on learning, writing, deploying and testing apex. for reference information on apex classes, interfaces, exceptions and so on, see apex reference guide. in this section: apex release notes use the salesforce release notes to learn about the most recent updates and changes to apex. getting started with apex learn about the apex development lifecycle. follow a step-by-step tutorial to create an apex class and trigger, and deploy them to a production organisation. writing apex apex is like java for salesforce. it enables you to add and interact with data in the lightning platform persistence layer. it uses classes, data types, variables, and if-else statements. you can make it execute based on a condition, or have a block of code execute repeatedly. running apex you can access many features of the salesforce user interface programmatically in apex, and you can integrate with external soap and rest web services. you can run apex code using a variety of mechanisms. apex code runs in atomic transactions. debugging, testing, and deploying apex develop your apex code in a sandbox and debug it with the developer console and debug logs. unit-test your code, then distribute it to customers using packages. apex reference in summer ’21 and later versions, apex reference content is moved to a separate guide called the apex reference guide. appendices glossary apex release notes use the salesforce release notes to learn about the most recent updates and changes to apex. for apex updates and changes that impact the salesforce platform, see the apex release notes. for new and changed apex classes, methods, exceptions and interfaces, see apex: new and changed items in the salesforce release notes. getting started with apex learn about the apex development lifecycle. follow a step-by-step tutorial to create an apex class and trigger, and deploy them to a production organisation. 1apex developer guide introducing apex in this section: introducing apex apex code is the first multitenant, on-demand programming language for developers interested in building the next generation of business applications. apex revolutionizes the way developers create on-demand applications. apex development process in this chapter, you’ll learn about the apex development lifecycle, and which organization and tools to use to develop apex
. you’ll also learn about testing and deploying apex code. apex quick start this step-by-step tutorial shows how to create a simple apex class and trigger, and how to deploy these components to a production organization. introducing apex apex code is the first multitenant, on-demand programming language for developers interested in building the next generation of business applications. apex revolutionizes the way developers create on-demand applications. 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 salesforce servers, they are restricted by the performance costs of making multiple round-trips to the salesforce site to accomplish common business transactions, and by the cost and complexity of hosting server code, such as java or .net, in a secure and robust environment. in this section: 1. what is apex? apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on salesforce servers in conjunction with calls to the 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. 2. understanding apex core concepts apex code typically contains many things that you might be familiar with from other programming languages. 3. 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. in this case, lightning platform provides various ways for advanced administrators and developers to build custom functionality. 4. how does apex work? all apex runs entirely on-demand on the lightning platform. developers write and save apex code to the platform, and end users trigger the execution of the apex code via the user interface. 5. developing code in the cloud the apex programming language is saved and runs in the cloud—the 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. 2apex developer guide introducing apex what is apex? apex is a strongly typed, object-oriented programming language that allows developers to execute editions flow and transaction control statements on salesforce servers in conjunction with calls to the api. using syntax that looks like java and acts like database stored procedures, apex enables developers available in: salesforce to add business logic to most system events, including button clicks, related record updates, and classic (not available in all visualforce pages. apex code can be initiated by web service requests and from triggers on objects. orgs) and lightning experience available in: enterprise, performance, unlimited, developer, and database.com editions you can add apex to most system events. as a language, apex is: integrated apex provides built-in support for common lightning platform idioms, including: • data manipulation language (dml) calls, such as insert, update, and delete, that include built-in dmlexception handling 3apex developer guide introducing apex • 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 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. where apex introduces new elements, it uses syntax and semantics that are easy to understand and encourage efficient use of the lightning platform. therefore, apex produces code that is both succinct and easy to write. data focused apex is designed to thread together multiple query and
dml statements into a single unit of work on the salesforce server. developers use database stored procedures to thread together multiple transaction statements on a database server in a similar way. 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. it stores all custom field, object, and class dependencies in metadata to ensure that they are not deleted while required by active apex code. hosted apex is interpreted, executed, and controlled entirely by the lightning platform. multitenant aware like the rest of the lightning platform, apex runs in a multitenant environment. so, the apex runtime engine is designed to guard closely against runaway code, preventing it from monopolizing shared resources. any code that violates limits fails with easy-to-understand error messages. easy to test apex provides built-in support for unit test creation and execution. it includes test results that indicate how much code is covered, and which parts of your code could be more efficient. salesforce ensures that all custom apex code works as expected by executing all unit tests prior to any platform upgrades. versioned you can save your apex code against different versions of the api. this enables you to maintain behavior. apex is included in performance edition, unlimited edition, developer edition, enterprise edition, and database.com. understanding apex core concepts apex code typically contains many things that you might be familiar with from other programming languages. 4apex developer guide introducing apex 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 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. for more information about using version settings with managed packages, see about package versions in the salesforce online help. 5apex developer guide introducing apex 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 lightning 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 fact 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 passed into methods by reference. therefore, when the method returns, the passed-in argument still
references the same object as before the method call. within the method, the reference can't be changed to point to another object, but the values of the object's fields can be changed. 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 • conditional (if-else) • loops: – do-while – while – for • locking • data manipulation language (dml) • transaction control • method invoking • exception handling 6apex developer guide introducing apex 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. . .]};] | ; 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 28. 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 7apex developer guide introducing apex 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 31. 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. 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 51. 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 8apex developer guide introducing apex • 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 55. 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. in this case, lightning platform provides various ways for advanced administrators and developers to build custom functionality. 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). • 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. lightning components develop lightning components to customize lightning experience, the salesforce mobile app, or to build your own standalone apps. you can also use out-of-the-box components to speed up development. as of spring ’19 (api version 45.0), you can build lightning components using two programming models: the lightning web components model, and the original aura components model. lightning web components are custom html elements built using html and modern javascript. lightning web components and aura components can coexist and interoperate on a page.configure lightning web components and aura components to work in lightning app builder and experience builder. admins and end users don’t know which programming model was used to develop the components. to them, they’re simply lightning components. for more information, see the component library. 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. 9apex developer guide introducing apex 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 guide. how does apex work? all apex runs entirely on-demand on the lightning platform. developers write and save apex code to the platform, and end users trigger the execution of the apex code via the user interface. apex is compiled, stored, and run entirely on the lightning 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. developing code in the cloud the apex programming language is saved and runs in the cloud—the 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. apex cannot be used
to: • render elements in the user interface other than error messages • change standard functionality—apex can only prevent the functionality from happening, or add additional functionality • create temporary files • spawn threads tip: all apex code runs on the lightning 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. 10apex developer guide apex development 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 don’t, you may run into the governor limits. see also: trigger and bulk request best practices apex development process in this chapter, you’ll learn about the apex development lifecycle, and which organization and tools to use to develop apex. you’ll also learn about testing and deploying apex code. in this section: what is the apex development process? to develop apex, get a developer edition account, write and test your code, then deploy your code. create a developer or sandbox org you can run apex in a production org, a developer org, or a sandbox org. you can develop apex in a developer org or a sandbox org, but not in a production org. learning apex after you have your developer account, there are many resources available to you for learning about apex writing apex using development environments there are several development environments for developing apex code. the developer console and the salesforce extensions for visual studio code allow you to write, test, and debug your apex code. the code editor in the user interface enables only writing code and doesn’t support debugging. 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. deploying apex to a sandbox organization sandboxes create copies of your salesforce org in separate environments. use them for development, testing, and training without compromising the data and applications in your production org. sandboxes are isolated from your production org, so operations that you perform in your sandboxes don’t affect your production org. 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. adding apex code to a appexchange app you can include an apex class or trigger in an app that you are creating for appexchange. what is the apex development process? to develop apex, get a developer edition account, write and test your code, then deploy your code. we recommend the following process for developing apex: 1. obtain a developer edition account. 11apex developer guide apex development process 2. learn more about apex. 3. write your apex. 4. while writing apex, you should also be writing tests. 5. optionally deploy your apex to a sandbox organization and do final unit tests. 6. 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 appexchange app package. create a developer or sandbox org you can run apex in a production org, a developer org, or a sandbox org. you can develop apex in a developer org or a sandbox org, but not in a production org. • production org—an org that has live users accessing your data • developer org—an org created with a developer edition account • sandbox org—an org created on your production org that is a copy of your production org 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 org includes apex, deploy your code to your org using one of the deployment methods. you can't develop apex in your salesforce production org. live users accessing the system while you're developing can destabilize your data or corrupt your application. instead, do all your development work in either a sandbox or a developer edition org. if you aren't already a member of the developer community, go to https://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 org. even if you already have a professional, enterprise, unlimited, or performance edition org and a sandbox for creating apex, we strongly recommend that you take advantage of the resources available in the developer community. note: you can’t modify apex using the salesforce user interface in a salesforce production org. to create a sandbox org: 1. from setup, enter sandboxes in the quick find box, then select sandboxes. 2. click new sandbox. 3. enter a name (10 characters or fewer) and description for the sandbox. we recommend that you choose a name that: • reflects the purpose of this sandbox, such as qa. • has only a few characters, because salesforce 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 you want. if your production org is hosted on an eligible hyperforce instance, our quick create technology enhances the speed at which a full sandbox is created. if you don’t see a sandbox option or need licenses for more, contact salesforce to order sandboxes for your org. if you reduce the number of sandboxes you purchase, you’re required to match the number of your sandboxes to the number you purchased. for example, if you have two full sandboxes but purchased only one, you can’t create a full sandbox. instead, convert a full sandbox to a smaller one, such as a developer pro or developer sandbox, depending on which types you have available. 5. select the data to include in your partial copy or full sandbox. 12apex developer guide apex development process • for a partial copy sandbox, click next, and then select the template you created to specify the data for your sandbox. if you haven’t created a template for this partial copy sandbox, see create or edit sandbox templates. • for a full sandbox click next, and then decide how much data to include. – to include template-based data for a full sandbox, select an existing sandbox template. for more information, see create or edit sandbox templates – to include all data in a full sandbox, choose whether and how much field tracking history data to include, and whether to copy chatter data. chatter data includes feeds, messages, and topics and is used in many components that affect your sandbox copy. decreasing the amount of data you copy can significantly speed sandbox copy time. 6. to run scripts after each create and refresh for this sandbox, specify the apex class you previously created from the sandboxpostcopy interface. 7. click create. tip: try to limit changes in your production org while the sandbox copy proceeds. learning apex after you have your developer account, there are many resources available to you for learning about apex apex trailhead content beginning and intermediate programmers several trailhead modules provide tutorials on learning apex. use these modules to learn the fundamentals of apex and how you can use it on the lightning platform. use apex to add custom business logic through triggers, unit tests, asynchronous apex, rest web services, and visualforce controllers. quick start: apex apex basics & database apex triggers apex integration services apex testing asynchronous apex salesforce developers apex page beginning and advanced programmers the apex page on salesforce developers 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. lightning platform code samples and sdks beginning and advanced programmers open-source code samples and sdks, reference code, and best practices can be found at code samples and sdks. a library of concise, meaningful examples of apex code for common use cases, following best practices, can be found at apex-recipes. development life cycle: enterprise development on the lightning platform architects and advanced programmers the application lifecycle and development models module on trailhead helps you learn how to use the application lifecycle and development models on the lightning platform. training courses training classes are also available from salesforce trailhead academy. grow and validate your skills with salesforce credentials. 13apex developer guide apex development process in this book (apex developer's guide) beginning programmers can look at the following: • introducing apex, and in particular: – documentation conventions – core concepts – quick start tutorial • classes, objects, and interfaces • testing apex • execution governors and limits in addition, advanced programmers can 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 writing apex using development environments there are several development environments for developing apex code. the developer console and the salesforce extensions for visual studio code allow you to write, test, and debug your apex code. the code editor in the user interface enables only writing code and doesn’t support debugging. 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. the developer console supports these tasks: • writing code—you can add code using the source code editor. also, you can browse packages in your organization. • compiling code—when you save a trigger or class, the code is automatically compiled. any compilation errors will be reported. • debugging—you can view debug logs and set checkpoints that aid in debugging. • testing—you 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 performance—you can inspect debug logs to locate performance bottlenecks. • soql queries—you can query data in your organization and view the results using the query editor. • color coding and autocomplete—the source code editor uses a color scheme for easier readability of code elements and provides autocompletion for class and method names. salesforce extensions for visual studio code the salesforce extension pack for visual studio code includes tools for developing on the salesforce platform in the lightweight, extensible vs code editor. these tools provide features for working with development orgs (scratch orgs, sandboxes, and de orgs), apex, aura components, and visualforce. see the website for information about installation and usage. 14apex developer guide apex development process tip: if you want to 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 668 and using soap api to deploy apex on page 674. 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 an object, from the object’s management settings, go to triggers, click new, and then enter your code in the body text box. • for a class, from setup, enter apex classes in the quick find box, then select apex classes. click new, and then enter your code in the body text box. note: you can’t modify apex using the salesforce user interface in a salesforce production org. 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. see also: salesforce help: find object management settings 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, and send no emails. such methods are flagged with the @istest annotation in the method definition. unit test methods must be defined in test classes, that is, classes annotated with @istest. note: the @istest annotation on methods is equivalent to the testmethod keyword. as best practice, salesforce recommends that you use @istest rather than testmethod. the testmethod keyword may be versioned out in a future release. in addition, before you deploy apex or package it for the appexchange, the following must be true. • unit tests must cover at least 75% of your apex code, and all of those tests must complete successfully. note the following. – when deploying apex to a production organization, each unit test in your organization namespace is executed by default. – calls to system.debug aren’t counted as part of
apex code coverage. – test methods and test classes aren’t counted as part of apex code coverage. – while only 75% of your apex code must be covered by tests, don’t focus on the percentage of code that is covered. instead, make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. this approach ensures that 75% or more of your code is covered by unit tests. • every trigger must have some test coverage. • all classes and triggers must compile successfully. 15apex developer guide apex quick start for more information on writing tests, see testing apex on page 634. deploying apex to a sandbox organization sandboxes create copies of your salesforce org in separate environments. use them for development, testing, and training without compromising the data and applications in your production org. sandboxes are isolated from your production org, so operations that you perform in your sandboxes don’t affect your production org. to deploy apex from a local project in the salesforce extension for visual studio code to a salesforce organization, see salesforce extensions for visual studio code. 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. you can also use salesforce cli. see develop against any org for details. for more information, see 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 visual studio code editor to a salesforce organization, see salesforce extensions for visual studio code. 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 668, and build and release your app. adding apex code to a appexchange app you can 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 recommends that any appexchange package that contains apex be a managed package. for more information, see the 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” in the salesforce online help. apex quick start this step-by-step tutorial shows how to create a simple apex class and trigger, and how to deploy these components to a production organization. 16apex developer guide apex quick start once you have a developer edition or sandbox organization, you may want to learn some of the core concepts of apex. after reviewing the basics, you are ready to write your first apex program—a very simple class, trigger, and unit test. because apex is very similar to java, you may recognize much of the functionality. 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. this hello world sample requires custom objects. you can either create these on your own, or download the objects and apex code as an unmanaged package from the salesforce appexchange. to obtain the sample assets in your org, install the apex tutorials package. this package also contains sample code and objects for the shipping invoice example. note: there is a more complex shipping invoice example that you can also walk through. that example illustrates many more features of the language. in this section: 1. create a custom object in this step, you create a custom object called book with one custom field called price. 2. adding an apex class 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. 3. add an apex trigger 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. 4. add a test class 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. 5. deploying components to production in this step, you deploy the apex code and the custom object you created previously to your production organization using change sets. create a custom object in this step, you create a custom object called book with one custom field called price. prerequisites: a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. for more information about creating a sandbox org, see “sandbox types and templates” in the salesforce help. to sign up for a free developer org, see the developer edition environment sign up page. 1. log in to your sandbox or developer org. 2. from your management settings for custom objects, if you’re using salesforce classic, click new custom object, or if you’re using lightning experience, select create > custom object. 3. enter book for the label. 4. enter books for the plural label. 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. 17apex developer guide apex quick start 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. you’ve 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. see also: salesforce help: find object management settings adding an apex class 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. prerequisites: • a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. • the book custom object. 1. from setup, enter “apex classes” in the quick find box, then select 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 58. 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 method—you 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 methods, variables, and initialization code on page 67. 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. 18apex developer guide apex quick start 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 expression operators on page 38. 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. add an apex trigger 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. prerequisites: • a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. • the myhelloworld apex class. a trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the lightning 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 the object management settings for books, go to triggers, and then click new. 2. 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) { 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. 19apex developer guide apex quick start 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. see also: salesforce help: find object management settings add a test class 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. prerequisites: • a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. • the helloworldtrigger apex trigger. note: testing is an important part of the development process. before you can deploy apex or package it for appexchange, the following must be true. • unit tests must cover at least 75% of your apex code, and all of those tests must complete successfully. note the following. – when deploying apex to a production organization,
each unit test in your organization namespace is executed by default. – calls to system.debug aren’t counted as part of apex code coverage. – test methods and test classes aren’t counted as part of apex code coverage. – while only 75% of your apex code must be covered by tests, don’t focus on the percentage of code that is covered. instead, make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. this approach ensures that 75% or more of your code is covered by unit tests. • every trigger must have some test coverage. • all classes and triggers must compile successfully. 1. from setup, enter apex classes in the quick find box, then select apex classes and click new. 2. in the class editor, add this test class definition, and then click save. @istest private class helloworldtestclass { @istest static 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); 20apex developer guide apex quick start // 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 this way should only contain test methods and any methods required to support those test methods. one advantage to creating a separate class for testing is that classes defined with @istest don’t count against your org’s limit of 6 mb of apex code. you can also add the @istest annotation to individual methods. for more information, see @istest annotation on page 98 and execution governors and limits. the method validatehelloworld is defined using the @istest annotation. this annotation means that if changes are made to the database, they’re rolled back when execution completes. you don’t have to delete any test data created in the test method. note: the @istest annotation on methods is equivalent to the testmethod keyword. as best practice, salesforce recommends that you use @istest rather than testmethod. the testmethod keyword may be versioned out in a future release. first, the test method creates a 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; after 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. the system.debug statement 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 test verifies that the method applydiscount ran and produced the expected result. // test that the trigger correctly updated the price system.assertequals(90, b.price__c); 3. to run this test and view code coverage information, switch to the developer console. 4. in the developer console, click test > new run. 5. to select your test class, click helloworldtestclass. 6. to add all methods in the helloworldtestclass class to the test run, click add selected. 7. 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. 21apex developer guide apex quick start 8. the overall code coverage pane shows the code coverage of this test class. to view the percentage of lines of code in the trigger covered by this test, which is 100%, double-click the code coverage line for helloworldtrigger. because the trigger calls a method from the myhelloworld class, this class also has coverage (100%). to view the class coverage, double-click myhelloworld. 9. 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 method, and the price before and after the trigger. by now, you’ve completed all the steps necessary for writing some apex code with a test that runs in your development environment. in the real world, after you’ve tested your code and are satisfied with it, you want to deploy the code and any prerequisite components to a production org. the next step shows you how to do this deployment for the code and custom object you’ve created. see also: salesforce help: open the developer console deploying components to production in this step, you deploy the apex code and the custom object you created previously to your production organization using change sets. 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” in the salesforce online help. • “create and upload change sets” user permission to create, edit, or upload outbound 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. from setup, enter outbound changesets in the quick find box, then select outbound changesets. 2. if a splash page appears, click continue. 3. in the change sets list, click new. 4. enter a name for your change set, for example, helloworldchangeset, and optionally a description. click save. 5. in the change set components section, click add. 6. 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. log into your production organization. b. from setup, enter inbound change sets in the quick find box, then select inbound change sets. c. if a splash page appears, click continue. d. in the change sets awaiting deployment list, click your change set's name. 22apex developer guide writing apex e. 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. writing apex apex is like java for salesforce. it enables you to add and interact with data in the lightning platform persistence layer. it uses classes, data types, variables, and if-else statements. you can make it execute based on a condition, or have a block of code execute repeatedly. in this section: data types and variables apex uses data types, variables, and related language constructs such as enums, constants, expressions, operators, and assignment statements. control flow statements apex provides if-else statements, switch statements, and loops to control the flow of code execution. statements are generally executed line by line, in the order they appear. with control flow statements, you can make apex code execute based on a certain condition, or have a block of code execute repeatedly. working with data in apex you can add and interact with data in the lightning platform persistence layer. the sobject data type is the main data type that holds data objects. you’ll use data manipulation language (dml) to work with data, and use query languages to retrieve data, such as the (), among other things. data types and variables apex uses data types, variables, and related language constructs such as enums, constants, expressions, operators, and assignment statements. in this section: 1. data types in apex, all variables and expressions have a data type, such as sobject, primitive, or enum. 2. primitive data types apex uses the same primitive data types as soap api, except for higher-precision dec
imal type in certain cases. all primitive data types are passed by value. 3. collections collections in apex can be lists, sets, or maps. 4. 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 don’t otherwise have a numerical order. typical examples include the suit of a card, or a particular season of the year. 5. variables local variables are declared with java-style syntax. as with java, multiple variables can be declared and initialized in a single statement. 23apex developer guide data types and variables 6. constants apex constants are variables whose values don’t change after being initialized once. constants can be defined using the final keyword. 7. expressions and operators an expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. 8. assignment statements an assignment statement is any statement that places a value into a variable. 9. 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. data types in apex, all variables and expressions have a data type, such as sobject, primitive, or enum. • a primitive, such as an integer, double, long, date, datetime, string, id, or boolean (see primitive data types on page 24) • an sobject, either as a generic sobject or as a specific sobject, such as an account, contact, or mycustomobject__c (see working with sobjects on page 122 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 28) – a set of primitives (see sets on page 31) – 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 33) • objects created from user-defined apex classes (see classes, objects, and interfaces on page 58) • 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 595. primitive data types apex uses the same primitive data types as soap api, except for higher-precision decimal type in certain cases. all primitive data types are passed by value. all apex variables, whether they’re 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: 24apex developer guide data types and variables data type description blob a collection of binary data stored as a single object. you can convert this data type 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. always create date values with a system static method. you can add or subtract an integer value from a date value, returning a date value. addition and subtraction of integer values are the only arithmetic functions that work with date values. you can’t perform arithmetic functions that include two or more date values. instead, use the date methods. use the string.valueof() method to obtain the date without an appended timestamp. using an implicit string conversion with a date value results in the date with the timestamp appended. datetime a value that indicates a particular day and time
, such as a timestamp. always create datetime values with a system static method. you can add or subtract an integer or double value from a datetime value, returning a date value. addition and subtraction of integer and double values are the only arithmetic functions that work with datetime values. you can’t perform arithmetic functions that include two or more datetime values. instead, use the datetime methods. decimal a number that includes a decimal point. decimal is an arbitrary precision number. currency fields are automatically assigned the type decimal. if you don’t explicitly set the number of decimal places for a decimal, the item from which the decimal is created determines the decimal’s scale. scale is a count of decimal places. use the setscale method to set a decimal’s scale. • 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 number is first converted to a string. scale is then set using the number of characters after the decimal point. note: two decimal objects that are numerically equivalent but differ in scale (such as 1.1 and 1.10) generally do not have the same hashcode. use caution when such decimal objects are used in sets or as map keys. double 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 pi = 3.14159; double e = 2.7182818284d; scientific notation (e) for doubles isn’t supported. 25apex developer guide data types and variables data type description id any valid 18-character lightning platform record identifier. for example: id id='00300000003t2pgaa0'; if you set id to a 15-character value, apex converts the value to its 18-character representation. all invalid id values are rejected with a runtime exception. integer a 32-bit number that doesn’t 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 doesn’t include a decimal point. longs have a minimum value of -263 and a maximum value of 263-1. use this data type when you need a range of values wider than the range provided by integer. for example: long l = 2147483648l; object any data type that is supported in apex. apex supports primitive 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. 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 type—a 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 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, which can be used to construct a message. 26apex developer guide data types and variables data type description 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 salesforce help. escapesequences: 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 using the comparison operators ==, !=, <, <=, >, and >=. because apex uses soql comparison semantics, results for strings are collated according to the context user’s locale and aren’t case-sensitive. for more information, see expression operators. string methods: as in java, strings can be manipulated with several standard methods. for more information, see string class. 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. always create time values with a system static method. see time class. in addition, two non-standard primitive data types can’t 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 lightning 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 can’t 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. 27apex developer guide data types and variables versioned behavior changes in api version 16 (summer ’09) and later, apex uses the higher-precision decimal data type in certain types such as currency. see also: expression operators collections collections in apex can be lists, sets, or maps. note: there is no limit on the number of items a collection can hold. however, there is a general limit on heap size. in this section: lists a list is an ordered collection of elements that are distinguished by their indices. list elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. sets a set is an unordered collection of elements that do not contain any duplicates. set elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. 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 type—primitive types, collections, sobjects, user-defined types, and built-in apex types. 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. see also: execution governors and limits lists a list is an ordered collection of elements that are distinguished by their indices. list elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. this 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' 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 seven levels of nested collections inside it, that is, up to eight levels overall. 28apex developer guide data types and variables 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. 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 you’re using square brackets to add an element to a list, the list behaves like an array and isn’t elastic, that is, you won’t 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]; defines an integer list with memory allocated for six integers list<integer> ints = new integer[6]; 29apex developer guide data types and variables in this section: list sorting you can sort list elements and the sort order depends on the data type of the elements. 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"], 30apex developer guide data types and variables system.selectoption[value="a", label="united states", disabled="false"], system.selectoption[value="c", label="canada", disabled="false"]) sets a set is an unordered collection of elements that do not contain any duplicates. set elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. this 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 seven levels of nested collections inside it, that is, up to eight levels overall. to declare a set, use the set keyword followed by the primitive data type name within <> characters. for example: set<string> mystringset = new set<string>(); the following example shows how to create a set with two hardcoded string values. // defines a new set with two elements set<string> set1 = new set<string>{'new york', 'paris'}; to access elements in a set, use the system methods provided by apex. for example: // define a new set set<integer> myset = new set<integer>(); // add two elements to the set myset.add(1); myset.add(3); // assert that the set contains the integer value we added system.assert(myset.contains(1)); // remove the integer value from the set myset.remove(1); the following example shows how to create a set from elements of another set. // define a new set that contains the // elements of the set created in the previous example set<integer> myset2 = new set<integer>(myset); // assert that the set size equals 1 // note: the set from the previous example contains only one value system.assert(myset2.size() == 1); for more information, including a complete list of all supported set system methods, see set class. 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—you can’t access a set element at a specific index. you can only iterate over set elements. • the iteration order of set elements is deterministic, so you can rely on the order being the same in each subsequent execution of the same code. 31apex developer guide data types and variables 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 type—primitive types, collections, sobjects, user-defined types, and built-in apex types. this 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 seven levels of nested collections, that is, up to eight levels overall. 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. 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. 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. • the iteration order of map elements is deterministic. you can rely on the order being the same in each subsequent execution of the same code. however, we recommend to 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. 32apex developer guide data types and variables • 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. • a map object is serializable into json only if it uses one of the following data types as a key. – boolean – date – datetime – decimal – double – enum – id – integer – long – string – time 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. this is legal in apex: integer x = 1; this 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> {'alpha', 'beta'}; 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 don’t otherwise have a numerical order. typical examples include the suit of a card, or a particular season of the year. 33apex developer guide data types and variables although each value corresponds to a distinct integer value, the enum hides this implementation. hiding the implementation prevents any possible misuse of the values to perform arithmetic and so on. 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 would any other data type. for example: season southernhemisphereseason = season.winter; public season getsouthernhemisphereseason(season northernhemisphereseason) { if (northernhemisphereseason == season.summer) return southernhemisphereseason; //... } you can also define a class as an enum. when you create an enum class, 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. any webservice method can use enum types as part of their signature. in this case, the associated wsdl file includes definitions for the enum and its values, which the api client can use. 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 salesforce 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 system.getapplicationreadwritemode(). • 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. typical examples are the decimal divide method and the double round method. for more information, see rounding mode. 34apex developer guide data types and variables • system.soaptype: this enum is returned by the field describe result getsoaptype method. for more information, 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. you cannot add user-defined methods to enum values. variables local variables are declared with java-style syntax. as with java, multiple variables can be declared and initialized in a single statement. 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); 35apex developer guide data types and variables all variables are initialized to null if they aren’t 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 aren’t 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 isn’t 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 can’t 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++); 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: you’ll 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 you’re trying to compare a letter to a null value. 36apex developer guide data types and variables constants apex constants are variables whose values don’t change after being initialized once. constants can be defined using the final keyword. the final keyword 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(); } } for more information, see using the final keyword on page 82. expressions and operators an expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. in this section: expressions an expression is a construct made up
of variables, operators, and method invocations that evaluates to a single value. expression operators expressions can be joined to one another with operators to create compound expressions. safe navigation operator use the safe navigation operator (?.) to replace explicit, sequential checks for null references. this operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a nullpointerexception. operator precedence operators are interpreted in order, according to rules. comments both single and multiline comments are supported in apex code. see also: expanding sobject and list expressions 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: 37apex developer guide data types and variables • a literal expression. for example: 1 + 1 • a new sobject, apex object, list, set, or map. for example: new account(<field_initializers>) new integer[<n>] new account[]{<elements>} new list<account>() new set<string>{} new map<string, integer>() new myrenamingclass(string oldname, string newname) • any value that can act as the left-hand of an assignment operator (l-values), including variables, one-dimensional list positions, and most sobject or apex object field references. for example: integer i mylist[3] mycontact.name myrenamingclass.oldname • any sobject field reference that is not an l-value, including: – the id of an sobject in a list (see lists) – a set of child records associated with an sobject (for example, the set of contacts associated with a particular account). this type of expression yields a query result, much like soql and sosl queries. • a soql or sosl query surrounded by square brackets, allowing for on-the-fly evaluation in apex. for example: account[] aa = [select id, name from account where name ='acme']; integer i = [select count() from contact where lastname ='weissman']; list<list<sobject>> searchlist = [find 'map*' in all fields returning account (id, name), contact, opportunity, lead]; for information, see soql and sosl queries on page 157. • a static or instance method invocation. for example: system.assert(true) myrenamingclass.replacenames() changepoint(new point(x, y)); expression operators expressions can 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. the data type of x must match the data type of y and can’t be null. 38apex developer guide data types and variables operator syntax description += 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 can’t 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: x and y must be integers or doubles or a combination. x and y can’t 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: x and y must be integers or doubles or a combination. x and y can’t 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: x and y must be integers or doubles or a combination. x and y can’t 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. x and y can’t be null. &= 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. x and y can’t 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: x can’t be null. 39apex developer guide data types and variables operator syntax description && 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: • && has precedence over || • this operator exhibits short-circuiting behavior, which means y is evaluated only if x is true. • x and y can’t be null. || x || y 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 can’t be null. == 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. therefore: – string comparison using == is case-insensitive and is performed according to the locale of the context user – id comparison using == is case-sensitive and doesn’t 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 40apex developer guide data types and variables operator syntax description 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. as a result, 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 doesn’t 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. • x and y can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. > x > y greater than operator. if x is greater than 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. • x and y can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. 41apex developer guide data types and variables operator syntax description <= x <= y 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: • 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 can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. >= x >= y 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. • x and y can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. != x != y inequality operator. if the value of x doesn’t equal the value of y, the expression evaluates to true. otherwise the expression evaluates to false. note: • string comparison using != is case-insensitive • 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. 42apex developer guide data types and variables operator syntax description • 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 ycan be the literal null. • the comparison of any two values can never result in null. !== x !== y exact inequality operator. if x and y don’t 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, the operator 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, the operator 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. if a double is used, the result is a double. / x / y division operator. divides x, an integer or double, by y, another integer or double. 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. the positive equivalent + is also syntactically valid but doesn’t have a mathematical effect. 43apex developer guide data types and variables operator syntax description ++ 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 ++x postfixed (x++), the expression evaluates to the value of x before the increment. -- 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 --x 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. | 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. ^ 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 bitwise not or complement operator. toggles each binary digit of x, converting 0 to 1 and 1 to 0. boolean values are converted from true to false and vice versa. () (x) parentheses. elevates the precedence of an expression x so that it’s evaluated first in a compound expression. ?. x?.y safe navigation operator. short-circuits expressions that attempt to operate on a null value, and returns null
instead of throwing a nullpointerexception. if the left-hand side of the chain expression evaluates to null, the right-hand side of the chain expression isn’t evaluated. safe navigation operator use the safe navigation operator (?.) to replace explicit, sequential checks for null references. this operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a nullpointerexception. important: where possible, we changed noninclusive terms to align with our company value of equality. we maintained certain terms to avoid any effect on customer implementations. 44apex developer guide data types and variables if the left-hand-side of the chain expression evaluates to null, the right-hand-side isn’t evaluated. use the safe navigation operator (?.) in method, variable, and property chaining. the part of the expression that isn’t evaluated can include variable references, method references, or array expressions. note: all apex types are implicitly nullable and can hold a null value returned from the operator. examples • this example first evaluates a, and returns null if a is null. otherwise the return value is a.b. a?.b // evaluates to: a == null ? null : a.b • this example returns null if a[x] evaluates to null. if a[x] doesn’t evaluate to null and amethod() returns null, then this expression throws a nullpointerexception. a[x]?.amethod().afield // evaluates to null if a[x] == null • this example returns null if a[x].amethod() evaluates to null. a[x].amethod()?.afield • this example indicates that the type of the expression is the same whether the safe navigation operator is used in the expression or not. integer x = anobject?.anintegerfield; // the expression is of type integer because the field is of type integer • this example shows a single statement replacing a block of code that checks for nulls. // previous code checking for nulls string profileurl = null; if (user.getprofileurl() != null) { profileurl = user.getprofileurl().toexternalform(); } // new code using the safe navigation operator string profileurl = user.getprofileurl()?.toexternalform(); • this example shows a single-row soql query using the safe navigation operator. // previous code checking for nulls results = [select name from account where id = :accid]; if (results.size() == 0) { // account was deleted return null; } return results[0].name; // new code using the safe navigation operator return [select name from account where id = :accid]?.name; table 1: safe navigation operator use-cases allowed use-case example more information method or variable or parameter chains aobject?.amethod(); can be used as a top-level statement. 45apex developer guide data types and variables allowed use-case example more information using parentheses, for example in a cast. ((t)a1?.b1)?.c1() the operator skips the method chain up to the first closing parenthesis. by adding the operator after the parenthesis, the code safeguards the whole expression. if the operator is used elsewhere, and not after the parenthesis, the whole cast expression isn’t be safeguarded. for example, the behavior of //incorrect use of safe navigation operator ((t)a1?.b1).c1() is equivalent to: t ref = null; if (a1 != null) { ref = (t)a1.b1; } result = ref.c1(); sobject chaining string s = an sobject expression evaluates to null contact.account?.billingcity; when the relationship is null. the behavior is equivalent to string s = contact.account.billingcity. soql queries string s = [select lastname if the soql query returns no objects, then from contact]?.lastname; the expression evaluates to null. the behavior is equivalent to: list<contact> contacts = [select lastname from contact]; string s; if (contacts.size() == 0) { s = null; // new behavior when using safe navigation. earlier, this would throw an exception. } else if (contacts.size() == 1) { s = contacts.get(0).last
name; } else { // contacts.size() > 1 throw new queryexception(...); } 46
apex developer guide data types and variables you can’t use the safe navigation operator in certain cases. attempting to use the operator in these ways causes an error during compilation: • types and static expressions with dots. for example: – namespaces – {namespace}.{class} – trigger.new – flow.interview.{flowname} – {type}.class • static variable access, method calls, and expressions. for example: – aclass.astaticmethodcall() – aclass.astaticvariable – string.format('{0}', 'hello world') – page.{pagename} • assignable expressions. for example: – foo?.bar = 42; – ++foo?.bar; • soql bind expressions. for example: class x { public string query = 'xyz';} x x = new x(); list<account> accounts = [select name from account where name = :x?.query] list<list<sobject>> moreaccounts = [find :x?.query in all fields returning account(name)]; • with adderror() on sobject scalar fields. for example: contact c; c.lastname?.adderror('the field must have a value'); note: you can use the operator with adderror() on sobjects, including lookup and master-detail fields. operator precedence operators are interpreted in order, according to rules. apex uses the following operator precedence rules: precedence operators description 1 {} () ++ -- grouping and prefix increments and decrements 2 ~ ! -x +x (type) new unary operators, additive operators, type cast and object creation 3 * / multiplication and division 4 + - addition and subtraction 47apex developer guide data types and variables precedence operators description 5 << >> >>> shift operators 6 < <= > >= instanceof greater-than and less-than comparisons, reference tests 7 == != comparisons: equal and not-equal 8 & bitwise and 9 ^ bitwise xor 10 | bitwise or 11 && logical and 12 || logical or 13 = += -= *= /= &= <<= >>= >>>= assignment operators 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. an assignment statement generally takes one of 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]; • a de-referenced list element. for example: ints[0] = 1; accts[0].name = 'acme'; 48apex developer guide data types and variables • 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 writable 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 expression operators on page 38. 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: 1. integer 2. long 49apex developer guide data types and variables 3. double 4. 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. 50apex developer guide control flow statements control flow statements apex provides if-else statements, switch statements, and loops to control the flow of code execution. statements are generally executed line by line, in the order they appear. with control flow statements, you can make apex code execute based on a certain condition, or have a block of code execute repeatedly. in this section: conditional (if-else) statements the conditional statement in apex works similarly to java. switch statements apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly. loops apex supports five types of procedural loops. 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; } 51apex developer guide control flow statements switch statements apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly. the syntax is: switch on expression { when value1 { // when block 1 // code block 1 } when value2 { // when block 2 // code block 2 } when value3 { // when block 3 // code block 3 } when else { // default block, optional // code block 4 } } the when value can be a single value, multiple values, or sobject types. for example: when value1 { } when value2, value3 { } when typename variablename { } the switch statement evaluates the expression and executes the code block for the matching when value. if no value matches, the when else code block is executed. if there isn’t a when else block, no action is taken. note: there is no fall-through. after the code block is executed, the switch statement exits. apex switch statement expressions can be one of the following types. • integer • long • sobject • string • enum when blocks each when block has a value that the expression is matched against. these values can take one of the following forms. • when literal {} (a when block can have multiple, comma-separated literal clauses) • when sobjecttype identifier {} • when enum_value {} the value null is a legal value for all types. 52apex developer guide control flow statements each when value must be unique. for example, you can use the literal x only in one when block clause. a when block is matched one time at most. when else block if no when values match the expression, the when else block is executed. note: salesforce recommends including a when else block, especially with enum types, although it isn’t required. when you build a switch statement using enum values provided by a managed package, your code might not behave as expected if a new version of the package contains additional enum values. you can prevent this problem by including a when else block to handle unanticipated values. if you include a when else block, it must be the last block in the switch statement. examples with literals you can use literal when values for switching on integer, long, and string types. string clauses are case-sensitive. for example, “orange” is a different value than “or
ange.” single value example the following example uses integer literals for when values. switch on i { when 2 { system.debug('when block 2'); } when -3 { system.debug('when block -3'); } when else { system.debug('default'); } } null value example because all types in apex are nullable, a when value can be null. switch on i { when 2 { system.debug('when block 2'); } when null { system.debug('bad integer'); } when else { system.debug('default ' + i); } } multiple values examples 53apex developer guide control flow statements the apex switch statement doesn’t fall-through, but a when clause can include multiple literal values to match against. you can also nest apex switch statements to provide multiple execution paths within a when clause. switch on i { when 2, 3, 4 { system.debug('when block 2 and 3 and 4'); } when 5, 6 { system.debug('when block 5 and 6'); } when 7 { system.debug('when block 7'); } when else { system.debug('default'); } } method example instead of switching on a variable expression, the following example switches on the result of a method call. switch on someinteger(i) { when 2 { system.debug('when block 2'); } when 3 { system.debug('when block 3'); } when else { system.debug('default'); } } example with sobjects switching on an sobject value allows you to implicitly perform instanceof checks and casting. for example, consider the following code that uses if-else statements. if (sobject instanceof account) { account a = (account) sobject; system.debug('account ' + a); } else if (sobject instanceof contact) { contact c = (contact) sobject; system.debug('contact ' + c); } else { system.debug('default'); } you can replace and simplify this code with the following switch statement. switch on sobject { when account a { system.debug('account ' + a); } when contact c { 54apex developer guide control flow statements system.debug('contact ' + c); } when null { system.debug('null'); } when else { system.debug('default'); } } note: you can use only one sobject type per when block. example with enums a switch statement that uses enum when values doesn’t require a when else block, but it is recommended. you can use multiple enum values per when block clause. switch on season { when winter { system.debug('boots'); } when spring, summer { system.debug('sandals'); } when else { system.debug('none of the above'); } } loops apex supports five types of procedural loops. these types of procedural loops are supported: • 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 in this section: 1. do-while loops 2. while loops 3. for loops 55apex developer guide control flow statements 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: • the traditional for loop: for (init_stmt; exit_condition; increment_stmt) { code_block } 56apex developer guide control flow statements • 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. in this section: traditional for loops list or set iteration for loops iterating collections 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. 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); } 57apex developer guide classes, objects, and interfaces 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. classes, objects, and interfaces apex classes are modeled on their counterparts in java. you’ll define, instantiate, and extend
classes, and you’ll work with interfaces, apex class versions, properties, and other related class concepts. in this section: 1. 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. 58apex developer guide classes, objects, and interfaces 2. interfaces an interface is like a class in which none of the methods have been implemented—the 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. 3. keywords apex provides the keywords final, instanceof, super, this, transient, with sharing and without sharing. 4. annotations an apex annotation modifies the way that a method or class is used, similar to annotations in java. annotations are defined with an initial @ symbol, followed by the appropriate keyword. 5. classes and casting in general, all type information is available at run time. 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 subclass of the other class. use casting when you want to convert an object from one data type to another. 6. differences between apex classes and java classes apex classes and java classes work in similar ways, but there are some significant differences. 7. class definition creation use the class editor to create a class in salesforce. 8. namespace prefix the salesforce application supports the use of namespace prefixes. namespace prefixes are used in managed appexchange packages to differentiate custom object and field names from names used by other organizations. 9. apex code versions to aid backwards-compatibility, classes and triggers are stored with the version settings for a specific salesforce api version. 10. 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. 11. using custom types in map keys and sets you can add instances of your own apex classes to maps and sets. 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 object—what it knows—includes the user who sent it, the date and time it was created, and whether it was flagged as important. the behavior of a purchaseorder object—what it can do—includes 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. 59apex developer guide classes, objects, and interfaces an interface is like a class in which none of the methods have been implemented—the 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 in addition to classes, apex provides triggers, similar to database triggers. a trigger is apex code that executes before or after database operations. see triggers. in this section: 1. apex class definition 2. class variables 3. class methods 4. using constructors 5. access modifiers 6. static and instance methods, variables, and initialization code in apex, you can have static methods, variables, and initialization code. however, apex classes can't be static. you can also have instance methods, member variables, and initialization code, which have no modifier, and local variables. 7. apex properties 8. extending a class you can extend a class to provide more specialized behavior. 9. extended class example 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 don’t 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 or implementations or both 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. 60apex developer guide classes, objects, and interfaces use the following syntax for defining classes: private | public | global [virtual | abstract | with sharing | without sharing] class classname [implements interfacenamelist] [extends classname] { // 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 classes—that is, if you don't specify an access modifier for an inner class, it’s considered private. this keyword can only be used with inner classes (or with top-level test classes marked with the @istest annotation). • 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 containing 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, without sharing, and inherited sharing keywords on page 86. • the virtual definition modifier declares that this class allows extension and overrides. you can’t 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 can’t 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 can’t 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 675. a class can implement multiple interfaces, but only extend one existing class. this restriction means that apex doesn’t support multiple inheritance. the interface names in the list are separated by commas. for more information about interfaces, see interfaces on page 78. for more information about method and variable access modifiers, see access modifiers on page 66. see also: documentation typographical conventions salesforce help: manage apex classes salesforce help: developer console functionality 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. 61apex developer guide classes, objects, and interfaces use the following syntax when defining a variable: [public | private | protected | global] [final] [static] data_type variable_name [= value] for example: private static final integer my_int; private final integer i = 1; versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. 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 doesn’t 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 use override to override methods only in classes that have been defined as virtual or abstract. 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 aren’t assigned to another variable. 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. • 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 aren’t needed. 62apex developer guide classes, objects, and interfaces • can be polymorphic. for example, a method named example 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 can’t find an exact match, it then seeks an approximate match using type coercion rules. for more information on data conversion, see rules of conversion on page 49. note: if the parser finds multiple approximate matches, a parse-time exception is generated. • methods with a void return type are typically invoked as a standalone statement 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 aren’t assigned to another variable. this rule is the same 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 fact 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 passed into methods by reference. therefore, when the method returns, the passed-in argument still references the same object as before the method call. within the method, the reference can't be changed to point to another object but the values of the object's fields can be changed. 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’s 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 reference into the reference() method and is modified. it then shows, in the referencenew() method, that the list argument can't be changed 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 statement ver
ifies 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 63apex developer guide classes, objects, and interfaces created list that contains new integer values. when the method returns, the original createme variable doesn't point to the new list but still points to the original list, which is empty. an assert statement verifies that createme contains no values. public class passnonprimitivetypeexample { 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}; } } versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. 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, a default, no-argument, public constructor 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. 64apex developer guide classes, objects, and interfaces 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 create your own no-argument constructor in your code. once you create a constructor for a class, you no longer have access to the default, no-argument public constructor. 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) {} 65apex developer guide classes, objects, and inter
faces // 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 aren’t as useful in smaller portions of apex. for example, declaring a method as global in an anonymous block doesn’t enable you to call it from outside of that code. for more information on class access modifiers, see apex class definition on page 60. note: interface methods have no access modifiers. they’re always global. for more information, see interfaces on page 78. by default, a method or variable is visible only to the apex code within the defining class. 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 access modifier is the default, and means that the method or variable is accessible only within the apex class in which it’s defined. if you don’t 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. this setting is strictly more permissive than the default (private) setting, just like java. public this means that the method or variable is accessible by all apex within a specific package. for accessibility by all second-generation (2gp) managed packages that share a namespace, use public with the @namespaceaccessible annotation. using the public access modifier in no-namespace packages implicitly renders the apex code as @namespaceaccessible. note: in apex, the public access modifier isn’t 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 must use the global access modifier. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. 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 must be used for any method that must be referenced outside of the application, either in 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. 66apex developer guide classes, objects, and interfaces to use the private, protected, public, or global access modifiers, use the following syntax: [(none)|private|protected|public|global] declaration for example: // private variable s1 private string s1 = '1'; // public method getsz() public string getsz() { ... } static and instance methods, variables, and initialization code in apex, you can have static methods, variables, and initialization code. however, apex classes can't be static. you can also have instance methods, member variables, and initialization code, which have no modifier, and local variables. characteristics static methods, variables, and initialization code have these characteristics. • they’re associated with a class. • they’re allowed only in outer classes. • they’re initialized only when a class is loaded. • they aren’t transmitted as part of the view state for a visualforce page. instance methods, member variables, and initialization code have these characteristics. • they’re associated with a particular object. • they have no definition modifier. • they’re created with every object instantiated from the class in which they’re declared. local variables have these characteristics. • they’re associated
with the block of code in which they’re declared. • they must be initialized before they’re used. the following example shows 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 use static methods and variables only with outer classes. inner classes have no static methods or variables. a static method or variable doesn’t require an instance of the class in order to run. before an object of a class is created, all static member variables in a class are initialized, and all static initialization code blocks are executed. these items are handled in the order in which they appear in the class. a static method is used as a utility method, and it never depends on the value of an instance member variable. because a static method is only associated with a class, it can’t access the instance member variable values of its class. 67apex developer guide classes, objects, and interfaces a static variable is static only within the scope of the apex transaction. it’s not static across the server or the entire organization. the value of a static variable persists within the context of a single transaction and is reset across transaction boundaries. for example, if an apex dml request causes a trigger to fire multiple times, the static variables persist across these trigger invocations. to store information that is shared across instances of a class, use a static variable. all instances of the same class share a single copy of the static variable. for example, all triggers that a single transaction spawns can communicate with each other by viewing and updating static variables in a related class. a recursive trigger can use the value of a class variable to determine when to exit the recursion. suppose that 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; } } } } a static variable defined in a trigger doesn't retain its value between different trigger contexts within the same transaction, such as between before insert and after insert invocations. instead, define the static variables in a class so that the trigger can access these class member variables and check their static values. a class static variable can’t be accessed through an instance of that class. if class myclass has a static variable mystaticvariable, and myclassinstance is an instance of myclass, myclassinstance.mystaticvariable isn’t a legal expression. the same is true for instance methods. if mystaticmethod() is a static method, myclassinstance.mystaticmethod() isn’t legal. instead, refer to those static identifiers using the class: myclass.mystaticvariable and myclass.mystaticmethod(). local variable names are evaluated before class names. if a local variable has the same name as a class, the local variable hides methods and variables on the class of the same name. for example, this method works if you comment out the string line. but if the string line is included the method doesn’t compile, because salesforce reports that the method doesn’t exist or has an incorrect signature. public static void method() { string database = ''; database.insert(new account()); } an inner class behaves like a static java inner class, but doesn’t require the static keyword. an inner class can have instance member variables like an outer class, but there’s no implicit pointer to an instance of the outer class (using the this keyword). note: in api version 20.0 and earlier, if a bulk api request causes a trigger to fire, each chunk of 200 records for the trigger to process is split into chunks of 100 records. in salesforce api version 21.0 and later, no further splits of api chunks occur. if a bulk api request causes a trigger to fire multiple times for chunks of 200 records, governor limits are reset between these trigger invocations for the same http request. 68apex developer guide classes, objects, and interfaces using instance methods and variables instance methods and member variables are used by an instance of a class, that is, by an object. an instance member variable is declared inside a class, but not within a method. instance methods usually use instance member variables to affect the behavior of the method
. suppose that you want to have a class that collects two-dimensional points and plots them on a graph. the following skeleton class uses 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 } the instance initialization code in a class is executed each time an object is instantiated from that class. these code blocks run before the constructor. if you don’t want to write your own constructor for a class, you can use an instance initialization code block to initialize instance variables. in simple situations, use an ordinary initializer. reserve initialization code for complex situations, such as initializing a static map. a static initialization block runs only one time, regardless of how many times you access the class that contains it. 69apex developer guide classes, objects, and interfaces 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 one time 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, just as they are in java. you can use static initialization code to initialize static final variables and to declare 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)); } } versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. 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’s accessed or returned. properties can be used to validate data before a change is made, to prompt an action when data is changed (such as altering the value of other member variables), or to 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. 70apex developer guide classes, objects, and interfaces if a property has only a get accessor, it’s considered read-only. if a property has only a set accessor, it’s considered write-only. a property with both accessors is considered read-write. 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 66. • return_type is the type of the property, such as integer, double, sobject, and so on. for more information, see data types on page 24. • 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 basicproperty class, exercising the get and set accessors: basicproperty bp = new basicproperty(); bp.prop = 5; // calls set accessor system.assertequals(5, bp.prop); // 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 not change the state of the object that it’s 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. • in api version 42.0 and later, unless a variable value is set in a set accessor, you can’t update its value in a get accessor. • 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 can’t be defined on interface. 71apex developer guide classes, objects, and interfaces • apex properties are based on their counterparts in c#, with the following differences: – properties provide storage for values directly. you don’t need to create supporting members for storing values. – it’s possible to create automatic properties in apex. for more information, see using automatic properties on page 72. using automatic properties properties don’t 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.assertequals(5, ap.mywriteonlyprop); // 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. therefore, accessors don’t 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 { private static integer staticmember; private integer nonstaticmember; // the following produces a system error // public static integer mybadstaticprop { return nonstaticmember; } public static integer mygoodstaticprop { get {return staticmember;} set { staticmember = value; } } public integer mygoodnonstaticprop { get {return nonstaticmember;} set { nonstaticmember = value; } } } 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; 72apex developer guide classes, objects, and interfaces // 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 can’
t 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; } // 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 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 you’re 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 the yellowmarker class extends the marker class. to run the inheritance examples in this section, first create the marker class. public virtual class marker { public virtual void write() { system.debug('writing some text.'); } public virtual double discount() { return .05; } } then create the yellowmarker class, which extends the marker class. // 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 73apex developer guide classes, objects, and interfaces a different result than calling this method on the first object, because this method has been overridden. however, you can call the discount method on the second object even though this method isn't part of the yellowmarker class definition. but it’s part of the extended class, and hence, is available to the extending class, yellowmarker. run this snippet in the execute anonymous window of the developer console. 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(); the extending class can have more method definitions that aren't common with the original extended class. in this example, the redmarker class extends the marker class and has one extra method, computeprice, that isn't available for the marker class. to call the extra methods, the object type must be the extending class. before running the next snippet, create the redmarker class, which requires the marker class in your org. // 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 snippet shows how to call the additional method on the redmarker class. run this snippet in the execute anonymous window of the developer console. redmarker obj = new redmarker(); // call method specific to redmarker only double price = obj.computeprice(); extensions also apply to interfaces—an 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. versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. 74apex developer guide classes, objects, and interfaces 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 // 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 75apex developer guide classes, objects, and interfaces 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 { // 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; } } 76apex developer guide classes, objects, and interfaces // 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 77apex developer guide classes, objects, and interfaces • the protected access modifier • exceptions as first class objects with members, methods, and constructors 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) interfaces an interface is like a class in which none of the methods have been implemented—the 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 can 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. 78apex developer guide classes, objects, and interfaces 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. here’s 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; // it’s worth it being an employee! 10% discount } } note the following about the 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. any class that implements an interface must define all the methods contained in the interface. when you define a new interface, you’re defining a new data type. you can use an interface name in any place you can use another data type name. any object assigned to a variable of type interface must be an instance of a class that implements the interface, or a sub-interface data type. see also classes and casting on page 108. note: you can’t add a method to a global interface after the class has been uploaded in a managed - released package version. versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. in this section: 1. custom iterators 79apex developer guide classes, objects, and interfaces 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 this example, count is incremented by 1 every time the loop is executed. while (count < 11) { system.debug(count); count++; } using the iterator interface you can create a custom set of instructions for traversing a list through a loop. the iterator 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’s 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 aren’t currently supported in for loops. using custom iterators with iterable if you don’t 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 returns description iterator 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. 80apex developer guide classes, objects, and interfaces in the following example a custom iterator iterates through a collection: public class customiterator implements iterator<account>{ private list<account> accounts; private integer currentindex; public customiterator(list<account> accounts){ this.accounts = accounts; this.currentindex = 0; } public boolean hasnext(){ return currentindex < accounts.size(); } public account next(){ if(hasnext()) { return accounts[currentindex++]; } else { throw new nosuchelementexception('iterator has no more elements.'); } } } public class customiterable implements iterable<account> { public iterator<account> iterator(){ list<account> accounts = [select id, name, numberofemployees from account limit 10]; return new customiterator(accounts); } } the following is a batch job that uses an iterator: public class batchclass implements database.batchable<account>{ public iterable<account> start(database.batchablecontext info){ return new customiterable(); } public void execute(database.batchablecontext info, list<account> scope){ list<account> accstoupdate = new list<account>(); for(account acc : scope){ acc.name = 'changed'; acc.numberofemployees = 69; accstoupdate.add(acc); } update accstoupdate;
} public void finish(database.batchablecontext info){ } } 81apex developer guide classes, objects, and interfaces keywords apex provides the keywords final, instanceof, super, this, transient, with sharing and without sharing. in this section: 1. using the final keyword 2. using the instanceof keyword 3. using the super keyword 4. using the this keyword 5. using the transient keyword 6. using the with sharing, without sharing, and inherited sharing keywords use the with sharing or without sharing keywords on a class to specify whether sharing rules must be enforced. use the inherited sharing keyword on a class to run the class in the sharing mode of the class that called it. 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 inside a constructor. 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 run time 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. } 82apex developer guide classes, objects, and interfaces note: in apex saved with api version 32.0 and later, instanceof returns false if the left operand is a null object. for example, the following sample returns false. object o = null; boolean result = o instanceof account; system.assertequals(false, result); in api version 31.0 and earlier, instanceof returns true in this case. 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; } 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. 83apex developer guide classes, objects, and interfaces 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

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card