Apex coding basics for learners

Written by Prasanth Kumar Published on Updated on

Apex Coding Basics

Hope this page will help you to understand coding basic of the apex. Here in this post, I will explain class, datatypes, variables, and constants.

What is Apex class?

A class is the group of variables and methods. We can create a class in Salesforce in different ways. See the below post to know about apex class.

Apex Class – Simple Class to understand Apex

Data types & Variables – Coding basics

Data types are used to define variables and methods in classes. In Apex, all variables & expressions have one of the below data types. Those are 

  • Primitive data types (Integer, Boolean, String, …… etc.)
  • Enum (an enumerated list)
  • sObjects (sObject, or Account, contact, object__c….)
  • Collection (list, set, map)
  • Null (for the null constant. Which can be assigned to any variable.
  • An object created by the user – or system-defined classes.

1. Primitive data types: know more about primitive data types

2. Enumerated list or Enum data type: Enumerated list (or Enum) is an abstract data type that stores one value of a finite set of specified identifiers. To define Enum, use the enum keyword in the variable declaration and then define the list of values. You can use enums to specify a set of constants. Know more about Enum

3. sObjects: Know more about sObject types

4. Collection data types: Three types of collection are available in Apex

List: An ordered collection of primitives, sObjects, collections, or Apex objects based on indices.
Set: An unordered collection of unique primitives.
Map: A collection of unique, primitive keys that map to single values which can be primitives, sObjects, collections, or Apex objects.

Notes:
– Collections can have not more than 1000 elements.
– Lists and maps may contain other collections – Collections can only be nested up to five levels deep.
– Collections do not support adding or removing elements while iterating over the collections. Know more about collections

Variables – coding basics

Static keyword is used to define static variables to store data that is shared within the class.

– Static variables are not memory constants.
– All instances of the same class share a single copy of the static variable.
– This can be a technique used for setting flags to prevent recursive triggers.

What is final keyword? 

    Final keyword is used to define constants – this indicates that the variable can only be assigned once, either in the declaration itself or with a static initializer method if the constant is defined in the class.

private final Integer j=10;