Development Basic to Advance

Apex

What is Apex?

Ans: Apex is a Strongly typed, object - oriented programming language. Apex works like a database scripts and stored procedures. The syntax of Apex looks like Java. Java is case sensitive but Apex is not case sensitive

  • A Stored procedure is used to retrieve data, modify data, and delete data in database table. We don't need to write a whole SQL command each time you want to insert, update or delete in an SQL Database. A stored procedure is a precompiled set of one or more SQL statements which perform specific task.
  • Apex enables us to write custom business logic to most system events, including button clicks, related record updates, and visualforce pages.  
  • Data types in Apex: Integer, Decimal, Double, Long, Date, DateTime, Boolean, String, Blob, sObject, Object.
  • Apex provides built in support for 
    • DML calls to insert, update, delete a record.
    • Inline SOQL or SOSL statements for retrieving records.
    • Looping control structures that help with bulk processing.
  • Object-Oriented Programming: It is a methodology or paradigm to design a program using Classes and Objects.
  • Object: An Object can be defined as an instance of a class
    • Object means a real time entity which has some characteristics, based on that characters we say what type of object it is.
    • Example: Our PC. It has Keyboard, Screen, Touchpad based on these characters only we can say it is PC.
  • Class: Collection of Objects, Methods, Variables, Constructors and Blocks is called class.
How to create Apex class?
Ans: 
            Syntax: public class className{
                                             variables;
                                             constructors;
                                              Methods;
                                }   
        How to create an Object for class
                className objectNmae = new className();      

What is a Variable?
Ans:  variables are used to store information A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution.
    Variable Declaration Syntax: 
      AccessModifier Datatype VariableName = defaultValue(optional);
  • Local Variable :  A variable defined with in a block or method or constructor is called local variable.    
  • Instance Variable: The variables declared inside the class are called Instance variables. This varaiables can be accessed anywhere in the class.
    • If we want access Instance variables outside the class we have to use Object notation. ObjectName.VariableName
  • Static Variable : A variable declared with static keyword are called Static variables.
    • Static variables or methods can be accessed using ClassName only ClassName.Variable or MethodName.
Declaring a variable : Before we can use a variable in Apex we need to declare variable.
Declaring variable means defining its type and optionally, setting an initial value.
Every variable in Apex must have a name and its a data type.
Data types means  what type of the data, the variable will store.
String Name = 'Venkanna';
   
What is Access Modifier?
Ans: Access Modifier specifies the accessibility or scope of a Variable, Field, Method, Constructor or Class.
            Types of Access Modifiers
    • Private
    • Public
    • Protected
    • Global
    • Web Service

Access modifiers define the access level within the class. We have three types of access modifiers in Apex. These are public, private, and global.

Private:

If the access modifier is declared as ‘Private’, then this class will be local and this class cannot be accessed outside of that particular entity. By default, all the classes will have this modifier.


Public: If the access modifier is declared as ‘Public’ then this signifies that this class is accessible to the organization, along with the defined namespace.


Global: If the access modifier is declared as ‘global’ then this class will be accessible by all apex codes irrespective of the organization.                                              

What is Method?

Ans:  A Method is a group of statements which are written in a sequential order to perform a specific task.

  • A Method can return some value or return nothing
  • A Method can be declared inside the class only.
  • Syntax : AccessModifier ReturnType MethodName()
    • Eg: public Integer add()
Types of Methods
  1. Instance Method: Methods which are declared Inside class  are called Instance Methods. These methods can be accessed through object only. Private methods can be accessed inside the class without any object.
  2. Static Method: Methods which are declared with Static keyword are called Static Methods.
  3. Virtual Method: The methods which are declared with Virtual keyword are called virtual methods.
                    public virtual class virtualParentClass{
                                public void add(Integer a, Integer b){
                                    
                                 }
                                public void sub(Integer c, Integer d){
                                                      
                                 }
                      }
 * If we want override a virtual class we must use keyword extends.
 
                            public  class  virtualChildClass  extends  virtualParentClass {
                                      
                                 }    
The child class doesn't have any methods but, when we use extends all the methods which are declared      in Parent class  indirectly comes into exending class(ChildClass).
*  If the method is declared as private, it will not come into ChildClass.
*  If we want to override any method, that method should be declared with keyword Virtual
              public  virtual  Integer  add(Integer  a,  Integer  b)
          If we do not mention virtual keyword that method cannot be overridden.
*  In Child Class we must use override keyword if we want to override.
              public  override Integer add(Integer  a,  Integer  b)
*  In virtual methods overriding is optional(If we want we can override otherwise we cannot.)

        4. Abstract Method: If we want to declare a Abstract class we must use keyword Abstract.
             * Abstract methods should not have any body, but we can declare our methods.
              * In virtual class overriding is optional, but in Abstract class if we declare any method we must                   and should override that method. 
              * Let say we have declared 3 methods and overriding only 2 methods then it throws error. All                       the 3 methods must override.
*Method overloading: If one method is implemented more than once with same name and different        arguments and different return types then it is overloading.

What is Constructor?
Ans: Constructor is like method which is used to perform task while creating an object. It is used to create an Object.
  • Constructor name should be same as ClassName.
  • Constructor should not return any datatype even void also. 
  • If constructor declared as Private, Object cannot be created outside the class.
  • Every class has it's own default constructor.
  • Syntax : AccessModifier  className(parameter)
  • THIS keyword: It is used inside the constructor to access the same class instance variables and also used to call one method from other.
What are Collections in Salesforce?
Ans: Collection is a group of elements which stores data into a single variable. We have three types of collections.
  • List
  • Set
  • Map
What is Difference between Normal  FOR(integer i=0;i<=10;i++) loop and Enhanced FOR(Datatype  variablename : collection) loop?

Ans : Normal for loop can iterates no of times that we specify in Condition.
      Ex: Suppose we have 1000 values to iterate but if we specify only 100 in Condition(i.e i<=100) then loop will iterate for 100 values only, remaining it will not iterate.
    
    If we Write Enhanced for loop, it will take the size of collections and iterates according to the size.
   Ex: If we have 10 values, it will iterate 10 times.
          If we have 200 values, it will iterate 200 times. 

Object Oriented Programming (OOP)

OOP(Object Oriented Programming) is a methodology that provides a way of modularizing a program by creating partitioned memory area for both data and methods that can be used as a template for creating copies of such modules (objects) on demand.

Unlike procedural programming, here in the OOP programming model, programs are organized around objects and data rather than action and logic.
The main OOP principle are :

1.Encapsulation
2.Inheritance
3.Polymorphism

Encapsulation: the wrapping up of data and methods together is called encapsulation. For example, if we take a class we write the variables and methods inside the class. Thus, a class is binding them together. So a class is an example of encapsulation. It is also known as Data Hiding

Inheritance: It creates new classes from existing classes so that the new classes will acquire all the features of the existing classes is called Inheritance.
A good example of Inheritance in nature is parents producing the children and children inheriting the qualities of parents.

Polymorphism: Polymorphism represents one form in multiple forms. In programming, we can use a single variable to refer to objects of different objects which means that single variable you can refer in the second object can be an extension of the first object. Thus using that variable we call the methods of different objects. A method call can perform different tasks depending on the type of the object.


APEX FUNDAMENTALS

Data type :

A data type in the apex tells about what type of data can be stored in salesforce.
What is the range of data that can be stored:
       1. Primitive data type
       2. Collections
       3. Enums
       4. sObjects


1. Primitive data type :

These are the data types which are predefined by the Apex.
  • A primitive data types such as an Integer, Double, Long, Date, Date Time, String, ID or Boolean
  • All primitive data types are passed by value, not by reference.
  • All apex variable, whether they are class member variable, are initialised to null. Make sure that we initialise variable to an appropriate value before using them.

Apex primitive datatype include:-

Boolean
  • A value that can only be assigned true, false or null.
               Ex: Boolean isActive = False;
Date
  • A value that indicates a particular day date values contain no information about time. Date value must always be created with a system static method.
  • Ex: Date myDate = Date.newinstance (2013,05,15);
  • Output is 2012-05-15 00:00:00

Time and DateTime 


These are data types associated with date and time along with Date datatype. The Time data types stores time(hours, minutes, seconds and milliseconds). The Date datatypes stores dates (year month day). The DateTime datatype stores both dates and times.

Each of these classes has a newInstance method with which we can construct a particular date and time values.
  • Ex: Time t1 = newInstance(19,20,1,20);
  • Output is 19:20:01
We can also create dates and times from the current clock :

    • Date my = Datetime.now();
    • Date t = Date.today();

    The Date and Time classes also have instance methods for converting from one format to another :

      • Ex: Time t2 = Datetime.now().time();

      We can also manipulate the values by using a range of instance methods :

        • Ex: Date t3 = Date.today(0);
        •       Date Next = t3.addDays(30);
        we will get something like this as the output.
              2013-05-15 00:00:00
              2013-06-16 00:00:00

        Integer, Long, Double and Decimal : 
        • To store numeric values in a variable, declare variables variable with one of the numeric data types. Integer, Long, Double and Decimal.

        Integer: 
        • A 32-bit number that doesn’t include a decimal point Integer have a minimum value of -2, 147, 467, 678 and a maximum value of 2,147, 483, 647.


        Ex: Integer i = 1;


        Collections :

        Collections in Apex can be lists, sets, or maps.

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

        Lists
        A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data 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.


        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.


        Types of Operators:

        OperatorsDescriptionSyntax
        =operator (Assignment Operator) assigns the value of “y” to the value of “x” x = y
        +=+= operator (Addition assignment operator) adds the value of “y” to the value of “x” and then it reassigns the new value to “x”.x += y
        *=*= operator (Multiplication assignment operator)multiplies the value of “y” with the value of “x” and then it reassigns the new value to “x”.x *= y
        -=-= operator (Subtraction assignment operator) substract the value of “y” with the value of “x”, and then it reassigns the new value of “x”.  x -= y
        /=/= operator (Division assignment operator) divides the value of “x” with the value of “y” and then reassigns the new value of “x”.x /= y
        |=|= operator(OR Assignment operator), If “x” (Boolean), and “y” (Boolean) both are false, then “x” remains false.  x |= y
        &=&= operator, if “x” (Boolean), and “y” (Boolean) both are true, then “x” remains true.x &= y
        &&&& operator (AND logical operator) it shows “short-circuiting” behavior that means “y” is evaluated only if “x” is true.x && y
        |||| OR logical operator.x || y
        ==== Operator, if the value of “x” equals to the value of “y”, then the expression evaluates true.  x == y
        ====== operator, if “x” and “y” reference the same location in the memory, then the expression evaluates true.x === y
        ++++ Increment operator.X ++
             ---- Decrement operator.x --


        Comparison operators

         Comparison operators, as the name suggests, deal with the process of comparing two values and return a Boolean value that indicates whether the comparison was true or false. The most commonly used comparison operators are as follows.

        Equality ==

         The double equals symbol compares whether two values are equal, for example: 

        Boolean equal = 'John' == ‘John';//true
        Boolean notEqual = 5 == 4; //false

        In the above code the values on the left and right of the == are compared and if they are equal true is returned, otherwise false. 

        It should be noted that the comparison is by value and not by reference. So we are not checking that it is the same instance of a variable in memory, only that the variables have the same value, unless dealing with a user-defined type. This is a minor point for you to consider and for most developers will not need to be a concern, however, it is something you should be aware of. 

        Inequality != 

        The inequality operator is the reverse of the equality operator above and compares two values to make sure that they differ:

        Boolean notEqual = 'John' != 'Michelle'; //true
        Boolean equal = 6 != 6; //false

        Greater Than > 

        This operator compares two values and returns true if the left-hand value is larger than the right hand one:

        Boolean greater = 125 > 4; //true
        Boolean notGreater = 6 > 9; //false
        Boolean greaterEqual = 7 &gt; 7; //false

        Greater Than or Equal To >= 

        Similarly to the previous greater than the operator, this will return true if the left-hand value is greater than or equal to the right-hand value: 

        Boolean greater = 125 &gt;= 4; //true
        Boolean notGreater = 6 >= 9; //false
        Boolean greaterEqual = 7 >= 7; //true

        Less Than < 

        This is the reverse of the grater than the operator and returns true if the left-hand side is smaller than the right-hand side:

        Boolean less = 12 &lt; 20; //true
        Boolean notLess = 9 < 7; //false
        Boolean lessEqual = 5 < 5; //false

        Less Than or Equal To 

        Again, similar to the previous less than operator but returns true if the left-hand side is less than or equal to the right hand side value: 

        Boolean less = 12 &lt;= 20; //true
        Boolean notLess = 9 <= 7; //false
        Boolean lessEqual = 5 <= 5; //true

        Logical operators 

        Logical operators allow us to apply Boolean logic to combine multiple Boolean inputs to obtain a single Boolean output. There are three logical operators in Apex, AND, OR and NOT. 

        AND operator && 

        The double ampersand && AND logical operator will return true if both the left-hand side and right-hand side are true. The operator will short-circuit so that if the left-hand value is false, the right-hand value will not be evaluated: 

        Boolean bothTrue = true &amp;&amp; true; //true
        Boolean rightTrue = false && true; //false
        Boolean leftTrue = true && false; //false
        Boolean bothFalse = false && false; //false

        OR operator

         The double pipe1 || OR logical operator will return a true value if either the left or the right-hand side are true. For the operator to return false, both the left and right-hand values must be false:

        Boolean bothTrue = true &amp;&amp; true; //true
        Boolean rightTrue = false && true; //true
        Boolean leftTrue = true && false; //true
        Boolean bothFalse = false && false; //false

        Not operator ! (logical complement) 

        The “not” (sometimes called logical complement) operator, returns the inverse value for a Boolean variable: 

        Boolean x = true;
        Boolean y = !x; //y set to false

        Assignment operators 

        Assignment operators allow us to assign and set values of variables. We have already seen the basic = operator that sets a variable to the value following the equals sign. We have some additional operators we can use to manipulate values as we assign them. 

        Addition assignment += 

        The addition assignment operator will take the value on the right-hand side of the operator, add it to the left-hand side before assigning the new total to the variable on the left-hand side. For example: 

        Integer x = 5; x += 7; //x set to 12

        If the variable is of type String, we can append another String onto the end using the operator as shown below: 

        String greeting = 'Hello ';
        greeting += 'world'; //greeting is now 'Hello world'

        Subtraction assignment -= 

        The subtraction assignment operator is similar to the addition operator in action but subtracts instead of adds the value on the right-hand side: 

        Integer x = 9; x -= 5; //x set to 4

        Multiplicative assignment *= 

        Multiplicative assignment works in the same way as both the additive and subtractive assignment but multiplies the left and right-hand sides before assigning the total as the new value: 

        Integer x = 12; x *= 7; //x set to 84

        Divisive assignment /= 

        The final assignment operator we will look at is the divisive assignment operator which divides the left-hand side by the right and then assigns the new value: 

        Integer x = 8; x /= 4; //x set to 2



        Class :
        A class is a collection of data members and methods.

        Example 1 :
        =============================================
        Class student
         {
            Integer no; //======These are data members of class
            String name; //=====
          public void getDetails() //==== This is the method of the class
          {
            system.debug(‘roll no’ + no);
            system.debug(’name’ + name);
          }
        }
        =============================================

        Example 2 :
        =============================================
        Class Employee
         {
           Integer exp; //===== variable /data members of the class
           String department; //=====

         void show() //===== Method of the class
         {
            //Write the logic here
          }
        }
        =============================================

        To define an Apex Class specify the following :

        1. Access Modifiers :
        • You must use one of the access modifiers for top-level class (Public or Global).
        • You do not have to use access modifiers in the declaration of inner classes.
        2. Optional definition modifiers such as Virtual, abstract.

        3. Required: The keyword class followed by the class name.

        4.Optional extensions : AND / OR implementation.

        Syntax :
        =============================================
        private | public | global [virtual | abstract | with sharing | (none)]
        Class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)]
          
           {
              // The body of a class
           }

        =============================================

        APEX ACCESS MODIFIERS - With Sharing • Without Sharing

        Access Modifiers

        Private: 

        • If you declare a class as a private, it is only known to the block in which it is declared.
        • By default all the inner classes are private.

        Public:

        • If you declare a class as a public, this apex class is visible throughout your application and you can access the application anywhere.

        Global:

        • If you declare a class as a global, this apex class is visible to all the apex application in the application or outside the application.
        • Note: If a method or a class (inner) is declared as global then the top level class also must be declared as global.

        With Sharing:

        • If you declare a class as a With Sharing, sharing rules given to the current user will be taken into consideration and the user can access and perform the operations based on the permissions given to him on objects and fields. (field level security, sharing rules)

        Without Sharing:

        • If you declare a class as a Without Sharing then this apex class runs in system mode which means apex code has access to all the objects and fields irrespective of current users sharing rules, fields level security, object permissions.
        • Note: If the class is not declared as With Sharing or Without Sharing then the class is by default taken as Without Sharing.
        • Both inner class and outer classes can be declared as With Sharing.
        • If inner class is declared as With Sharing and top-level class is declared as without sharing, then the entire context will run in With Sharing context.
        • Outer class is declared as With Sharing and inner class is declared as Without Sharing then inner class runs in Without Sharing context only. (Inner classes don't take the sharing properties from outer class).

        Virtual:

        • If a class is declared with keyword Virtual then this class can be extended (Inherited) or this class method can be overridden by using a class called overridden.

        Abstract:

        • This class contains Abstract methods, which will provide common method implementation to all subclasses.
        Now let's see an example and understand how to use it in apex class.

        Example 1:
        =============================================
        public class outerclass
         {
           //code
           
            class innerclass
           {
              //Innerclass code
           }
        }
        =============================================

        Example 2:
        =============================================
        public with sharing class sharing class
        {
            //code
        }
          =============================================

          Example 3:
          =============================================
          public without sharing class noSharing
          {
             //code  
          }
          =============================================

          Example 4:
          =============================================
          public with sharing class outer
          {
            //outer class code

            without sharing class inner
            {
              //Inner class code
            }
          }
          =============================================

          In the above code outer class runs with current users sharing rules. But inner class runs with system context.

          Example 5:
          =============================================
          public without sharing class outer
          {
            //Outer class code
            with sharing class inner
            {
              //Inner class code 
            }
          }
          =============================================

          In this way, both the inner and outer classes run with current users permissions.

          APEX VARIABLE • METHODS • OBJECT

          CLASS VARIABLE :
          The variable in the class should specify the following properties when they are defined.

          Optional: 
          • Modifiers such as public or final as well as static. 
          • The value of the variable.
          • The name of a variable.
          Required: 
          • The data type of the variable, such as String or Boolean.
          Syntax :
          =================================================
          [ public | private | protected | global | final ] [static] data_type variable_name
          =================================================

          Example :
          =================================================
          private static final Integer My_INT;
          private final Integer i=1;
          =================================================

          CLASS METHODS : 

          To define a method, specify the following.

          Optional:
          • Modifiers, such as public or protected.
          Required:
          • The data type of the value returned by the method, such as String or Integer. Use void if the method does not return a value.
          • 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.
          • The body of the method, enclosed in braces { }. 
          • All the code for the method, including any local variable declarations, is contained here.
          Syntax:
            =================================================
            ( public | private | protected | global ) [override] [static] data_type method_name (input parameters) 
            {
               //The body of the method.
             }
            =================================================

            Example 1 :
            =================================================
            public static Integer getInt()
            {
              return MY_INT;
            }
            =================================================

            Example 2 :
            =================================================
            public class Example 
            {
              public Integer Show (Integer age)
              {
                System.debug('my age is' +age );
                }
            }
            =================================================

            In the above code, it will accept age value as an Integer type, for example, if the input is 20 then it will accept 20 and display the output as my age is 20.
              OBJECT :
              • The object is an instance of the class. This has both state and behaviour.
              • Memory for the data members is allowed only when you create an object.
              Syntax:
              =================================================
              classname objectname = new classname ();
              =================================================
              • classname This is the name of class for which we are creating an object.
              • objectname This is a reference variable.
              • new This is a keyword which we are allocating the memory.
              • () This is contructor.
              Example:
              =================================================
              class Example
              {
                 //your code here
              }
              Example e = new Example();
              =================================================

              In this way, you can use apex variable, method, object in salesforce.


              Constructor

              The constructor is a special method which has the following properties :
              • Method name will be the same as a class.
              • Access specifier will be public.
              • This method will be invoked only once that is at the time of creating an object.
              • This is used to instantiate the data members of the class.


              1.Constructor are used to initialize the state of object,where as method is expose the behaviour of object.
              2.Constructor must not have return type where as method must have return type.
              3.Constructor name same as the class name where as method may or may not the same class name.
              4.Constructor invoke implicitly where as method invoke explicitly.
              5.Constructor compiler provide default constructor where as method compiler does't provide.

              Example:-
               
              public class Apple {
                  //instance variables
                  String type; // macintosh, green, red, ...
              
                  /**
                   * This is the default constructor that gets called when you use
                   * Apple a = new Apple(); which creates an Apple object named a.
                   */
              
                  public Apple() {
                      // in here you initialize instance variables, and sometimes but rarely
                      // do other functionality (at least with basic objects)
                      this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
                  }
              
                  /**
                   * this is another constructor with a parameter. You can have more than one
                   * constructor as long as they have different parameters. It creates an Apple
                   * object when called using Apple a = new Apple("someAppleType");
                   */
                  public Apple(String t) {
                      // when the constructor is called (i.e new Apple() ) this code is executed
                      this.type = t;
                  }
              
                  /**
                   * methods in a class are functions. They are whatever functionality needed
                   * for the object
                   */
                  public String someAppleRelatedMethod(){
                      return "hello, Apple class!";
                  }
              
                  public static void main(String[] args) {
                      // construct an apple
                      Apple a = new Apple("green");
                      // 'a' is now an Apple object and has all the methods and
                      // variables of the Apple class.
                      // To use a method from 'a':
                      String temp = a.someAppleRelatedMethod();
                      System.out.println(temp);
                      System.out.println("a's type is " + a.type);
                  }
              }

              For Example :
              =================================================
              public class TestObject
               {
                 \\The no argument constructor

                  public TestObject()
                   {
                     \\code
                    }
                }
              =================================================

              There are 3 types of constructors:
              • 1. Default Constructor
              • 2. Non-parameterized Constructor
              • 3. Parameterized Constructor 

              1. Default Constructor

              If an Apex Class doesn't contain any constructor then Apex compiler by default creates a dummy constructor on the name of the class when we create an object for the class.

              For Example:
              =================================================
              public class Example
               {
                
                }
               Example e = new Example();

              =================================================

              In the above example, the apex class doesn't contain any constructor. So when we create an object for example class the Apex compiler creates a default constructor.

              For Example:
              =================================================
              public example()
              {

              }
              =================================================

              2. Non-parameterized Constructor

              • It is a constructor that doesn't have any parameters is called Non-parameterized constructor.
              • Parameters are nothing but the values we are passing inside a constructor.
              For Example:
              =================================================
              public class Example
              {
                Integer number;
                 String Name;

                 public Example()  //Non-parametarized Constructor
                 {
                  number=10;
                   name=Salesforcekid;
                 }

              }
              =================================================

              3. Parameterized Constructor 

              • It is a constructor that has parameters.
              • That means here we will take input from the user and then map it with our variable.
              For Example:
              =================================================
              public class Example
               {
                 Integer number;
                 String Name;

              public Example(Integer x, String myname) //Parametarized Constructor
               {
                 number = x;
                 Name = myname;
               }
              =================================================

              Now let's create an apex program to understand the use of constructor in an apex.
              • Open developer console by clicking the org name on the Salesforce page.
              • Click File --> New --> Apex Class.
              • Enter the class name.
              • Write the Apex Class.
              For Example:
              =================================================
              public class Employee //Class
               {
                 String EmployeeName;
                 Integer EmployeeNo;
                
                public Employee() //Constructor
                {
                  EmployeeName = 'Ajinkya';
                  EmployeeNo = 10;
                 }
               public void show() //Method
               {
                 System.debug('Employee Name is '+ EmployeeName);
                 System.debug('Employee No is '+ EmployeeNo);
                }

              }
              =================================================

              Now open anonymous window and type this 
                =================================================
                Employee c1 = new Employee();
                Employee c2 = new Employee();

                c1.show();
                c2.show();
                =================================================

                This will give you the following output
                  =================================================
                  EmployeeName is Ajinkya
                  EmployeeNo is 10


                  integer Sal=10000;

                  Decimal bonus,salafterbonus;

                  for(bonus=5;bonus<=20;bonus+=5)

                  {

                    salafterbonus=sal+(sal*(bonus/100));

                    system.debug('salafterbonus'+bonus+'%bonus='+salafterbonus);


                  ----------------------

                  for(integer i=20; i>=5;i-=5)

                  {

                      system.debug(i);

                  }


                  -------------  ----------------------

                  public class Dog 

                   {

                              public string Name='Scoopy';

                              public integer age=13;

                  public void disp()

                          {

                              system.debug('Name of the Dog'+Name);

                              system.debug('Age of my Dog'+age);

                          }

                    }

                  in Anonymous window :

                  Dog d1=new Dog();

                  system.debug(d1);


                  ---------------------   ---------------------

                  public class Dog 
                   {
                              public string Name;
                              public integer age;
                  public void disp()
                          {
                              system.debug('Name of the Dog'+Name);
                              system.debug('Age of my Dog'+age);
                          }
                    }

                  in Anonymous window :

                  Dog d1=new Dog();
                  d1.name='Scoopy';
                  d1.age=12;
                  d1.disp();

                  Dog d2=new Dog();
                  d2.name='Tiger';
                  d2.age=12;
                  d2.disp();

                  ---------------   -------------------

                  public class Employee 
                   {
                              public string Name;
                              public string Designation;
                  public void show()
                          {
                              system.debug('Name of the Emp'+Name);
                              system.debug('Designation'+designation);
                          }
                    }


                  in Anonymous window :

                  Employee e1=new Employee ();
                  Employee e2=new Employee ();
                  e1.name='Venkanna';
                  e1.designation='Senior Manager';
                  e2.name='Johny';
                  e2.designation='Manager';

                  e1.show();
                  e2.show();

                  --------------  -------------    --------------------

                  If else Statements

                  If else statements are used to control the conditional statement that are based on various conditions. It is used to execute the statement code block if the expression is true. Otherwise, it executes else statement code block.

                  Salesforce If else Statements

                  Syntax:if (Boolean_condition)

                  //Statement1

                  else

                  //statement 2

                  Example: Check the condition for voting


                  integer age=20; 

                  if(age>=18)    //checks the condition

                  {

                      System.debug('ELIGIBLE FOR VOTING');

                  }

                  else

                  {

                      System.debug('NOT ELIGIBLE');

                  }


                  -------------  ------

                  Example:


                  integer marks=28;

                  if(marks>=33)

                  {

                      System.debug('PASS');

                  }

                  else

                  {

                      System.debug('FAIL');

                  }


                  --------------------------

                  Example: Comparing two different ages        


                  integer age1=22;    //my age

                  integer age2=20;   //my brother`s age

                  if(age1>age2)

                  {

                      System.debug('I am elder');

                     }

                  else

                  {

                      System.debug('My brother is elder');

                  }

                  ----------------------------

                  If else if Statement

                  Syntax:


                  if (expression1)

                  {

                  //statement

                  else if(expression2)

                  {

                  //statement

                  }

                  else if(expression3)

                  {

                  //statement

                  }

                  ..

                  ..

                  ..

                  else

                  {

                  //statement

                  }  


                                

                  Example: Positive Number


                  integer num=10;

                  if(num>0)

                  {

                      System.debug('Number is positive');

                  }

                  else if(num<0)

                  {

                      System.debug('Number is negative');

                  }

                  else

                  {

                      System.debug('Number is Zero');

                  }

                  ------------------------  --------------------------------

                  Example: Negative Number

                  integer num = (-50);

                  if(num>0)

                  {

                      System.debug('Number is positive');

                     }

                  else if(num<0)

                  {

                      System.debug('Number is negative');

                  }

                  else

                  {

                      System.debug('Number is Zero');

                  }

                  -----------------------------  ---------------------

                  Example: Zero


                  integer num=(0);

                  if(num>0)

                  {

                      System.debug('Number is positive');

                  }

                  else if(num<0)

                  {

                      System.debug('Number is negative');

                  }

                  else

                  {

                      System.debug('Number is Zero');

                  }


                  ----------------- ---------------------------------

                  Example:


                  integer place=1;

                  String medal_color;

                  if(place ==1)

                  {

                      medal_color='gold';

                  }   

                  else if (place==2)

                  {

                      medal_color='silver';   

                  }

                  else if(place==3)

                  {

                      medal_color='bronze';

                  }

                  else

                  {

                     medal_color='null';

                  }

                  System.debug('You have scored '+medal_color + 'Medal. Congratulations');


                  ----------------- ---------------------------------

                  Example:


                  integer top_score=99,second_score=80,your_score=85;  

                  if(your_score>top_score)

                  {

                      System.debug('You have scored the highest marks');

                  }

                  else if((your_score<top_score)&& (your_score>second_score))

                  {

                      System.debug('You have scored greater than the second score');

                  }

                  else if((your_score<top_score)&&(your_score<second_score)&&(your_score>65))

                  {

                      System.debug('You can do better');

                  }  

                  else

                  {

                      System.debug('Work hard');

                  }


                  In the above example, we have created three integer variable top_score, second_score, your_score, and initialized them with 99, 80, 85 values.


                  In first if block, we are checking if your_score is greater than top_score i.e., 85>99, so the first if block will not get executed because the condition is false.


                  In the next else block, if your_score is less than top_score i.e., 99<85 (this condition is true) and the second condition is your_score is greater than second_score i.e., 85>80 (this condition is true).


                  There is a && operator. In the && operator, both the condition needs to be true. So, this block will get executed because both these conditions are true.


                  Once any of the blocks gets executed, the rest of the conditions will be skipped.

                  ----------------- ---------------------------------

                  Example:


                  integer salary=250000;

                  Decimal bonus,salary_after_bonus;

                  if(salary>=200000)

                  {

                      bonus=15;

                  }

                  else if(salary>=150000)

                  {

                      bonus=12;

                  }

                  else if(salary>=10000)

                  {

                      bonus=10;

                  }

                  else

                  {

                      bonus=5;

                  }

                  salary_after_bonus=salary+(salary*(bonus/100));

                  System.debug('Salary '+salary);

                  System.debug('Bonus '+bonus+ '%');

                  System.debug('Salary after bonus'+ salary_after_bonus);

                  **********************************************************

                  Switch Statements

                  A switch statement tests whether an expression matches one of the several cases.


                  Syntax:

                  switch(expression)x
                  value1
                  {
                  //statement
                  }
                  value2
                  {
                  //statement
                  }
                  value3
                  {
                  //statement
                  }
                  Default

                  Example:

                  integer num= 17;
                  switch on num
                  {
                      when 2{
                          system.debug('num is 4');
                      }
                      when -3
                      {
                        system.debug('num is -3'); 
                      }
                      when else{
                          system.debug('neither 2 nor -3');
                      }
                  }


                  Salesforce Switch Statements
                  Example:


                  integer place=1;
                  String medal_color;  //null
                  switch on place
                  {
                      when 1{
                          medal_color='gold';
                      }
                      when 2{
                          medal_color='silver';
                      }
                      when 3{
                          medal_color='bronze';
                      }
                      when else{
                          medal_color=null;
                      }
                  }
                  if(medal_color!=null)
                  {
                      System.debug('you have scored '+medal_color+ 'medal.Congratulations!!');
                  }
                   else
                   {
                      System.debug('Work hard');
                   }


                  Salesforce Switch Statements
                  Example:

                  integer score=95;
                  switch on score
                  {
                      when 80,85,90,95{
                          System.debug('FIRST PLACE');
                      }
                      when 75,70
                      {
                          System.debug('SECOND PLACE');
                      }
                      when 65,60,55
                      {
                          System.debug('THIRD PLACE');
                      }
                      when else
                      {
                          System.debug('Better luck');
                      }
                  }

                  ************************************
                  Loops in Apex

                  Looping is a feature that makes the execution of a set of functions multiple times, although some condition evaluates to true.


                  There are 3 types of loops:

                          While loop
                          For loop
                          Do-while loop

                  While loop:

                  A while loop is a control flow statement that allows code to be executed many times based on a given Boolean condition. The while loop can be thought as a repeating if statement.

                   Syntax:


                  while (Boolean condition)
                  {
                            Loop statements…
                  }
                  If the Boolean condition is true, then the loop statement will get executed, and if the boolean condition is false, then the control will come out outside of the loop.
                  Salesforce Loops in Apex

                  Example1:


                  integer i=1;

                  while(i<=10)

                  {

                      System.debug('Javatpoint');

                      i++;

                  }

                   

                  In the above example, we have created a variable called (i) and initialized the value of the variable to 1, then, it checks while 1 is less than or equals to 10(condition is true). Now it will display “Javatpoint” on the screen. The increment operator (i++) will increase the value of (i) by 1.


                  Example2:


                  integer i=1;

                  while(i<=10)

                  {

                      System.debug('value of i= '+1);

                      i++;

                  }


                  ------

                  Example3:


                  integer i=1;

                  while(i<=10)

                  {

                      System.debug('value of i= '+i);

                      i++;

                  }


                  ---------------------

                  Example4:


                  integer i=0;

                  while(i<=100)

                  {

                      System.debug('value of i= '+i);

                      i+=10;

                  }

                  ---------------------

                  Example5:


                  integer i=10;

                  while(i>=1)

                  {

                      System.debug('value of i= '+i);

                      i--;

                  }


                  For loop:


                  A for loop statement consumes the initialization, condition, and increment/decrement in one line by providing a shorter, easy to debug structure of looping.


                  Syntax:


                  for(initialization condition; testing condition; increment/decrement)

                  {

                          statement(s)

                  }


                  Salesforce Loops in Apex

                  The initialization will only get executed once.

                  The condition and increment/decrement will be executed again.

                  Once it initialized, it will check for the condition, if the condition is true, then the statement will get executed, and again it will increment/decrement.

                  Once it increment/decrement, then again we check for the condition, if the condition is still true, it will get executed.

                  Once the condition becomes false, then the loop will stop further execution.

                  Example:

                  for(integer i=1;i<=5;i++)

                  {

                      System.debug('value of i= '+i);

                  }




                  Example:


                  integer salary=150000;

                  Decimal bonus,salary_after_bonus;

                  for(bonus=10;bonus<=25;bonus+=5)

                  {

                      salary_after_bonus=salary+(salary*(bonus/100));

                      System.debug('Salary after '+bonus+ '% bonus '+salary_after_bonus);

                  }



                  Example: Even no. in reverse order.


                  for(integer i=10;i>=0;i=i-2)

                  {

                      System.debug('value of i= '+i);

                  }



                  Three different types of for loop in Apex:


                  Traditional for loop

                          Syntax:


                  for (init_stml; ext_condition; increment_stmt)

                  {

                            code_block

                  }

                  Set iteration for loop

                  Syntax:


                  for (variable : list_or_set)

                  {

                         code_block

                  }


                  SOQL for loop

                  Syntax:


                  for (variable : [soql_query ])

                  {

                         code_block

                  }


                  Example:


                  List<String> stuNames=new List<String>

                  {'John', 'Sam', 'Barak'};

                      for(String stuName:stuNames)

                  {

                      System.debug('name= '+stuName);

                  }


                  Example:


                  List<Integer> empIds=new List<Integer>

                  {1200,96000,85274,74523,87523};

                      for(Integer empId:empIds)

                  {

                      System.debug('empId= '+empId);

                  }


                  Break and Continue Statement:

                  Break statement: The break statement is used to jump out of a loop.


                  Continue statement:  The continue statement breaks one iteration in the loop (it will just skip the particular statement).


                  Example:


                  for(integer i=1;i<=20;i++)

                  {

                      if(i==10)

                      {

                          break;

                     }

                      System.debug('value of i= '+i);

                  }


                  In the above example, the break statement will come out of the loop once it hit the value 5.


                  Example:


                  for(integer i=1;i<=20;i++)

                  {

                      if(i==10)

                      {

                          continue;

                     }

                      System.debug('value of i= '+i);

                  }



                  In the above example, the continue statement skips the iteration (10) and jump to the next iteration.


                  Nested Loop:


                   Placing a loop inside another loop is called a nested loop.


                  Example:


                  for(integer i=0;i<=3;i++)

                  {

                      for(integer j=0;j<=2;j++)

                      {

                          System.debug('i ='+i+' j='+j);

                      }

                  }



                  Example:


                  for(integer i=1;i<=5;i++)

                  {

                      for(integer j=1;j<=i;j++)

                      {

                          System.debug(i);

                      }

                  }


                  ------------------------  -------------------------

                  Static and Non Static Method

                  public class StaticExample 

                  {

                  public static void method1()

                      {

                          system.debug('i m a static method');

                      }

                      public void method2()

                      {

                          system.debug('i m not a static method');

                      }

                  }

                  Static methods can be directly call with Class Name and dot operator

                   StaticExample.method1();    if run with this it runs fine and displays the result  




                  Non static methods can't call directly with class name, need to create object of the class to call the methods



                  ------------------  ---------------------------------

                  Static and Non-static variable



                  ---------------

                  Access Modifiers in Apex

                  public class Cat 
                  {
                   public string name;
                      public integer size;
                      public void display()
                      {
                          system.debug('Name of my Cat'+name);
                          system.debug('Size of my Cat'+size);
                      }
                  }



                  ----

                  public class Cat 

                  {

                    private string name;

                      private integer size;

                      public void setname(string n)

                      {

                          name=n;

                      }

                      public void setsize(integer s)

                      {

                          if(s<=0)

                          {

                             system.debug('you cant set a wrong value for my cat');

                                  size=10;

                          }

                          else

                          {

                              size = s;

                          }

                      }

                      public void display()

                      {

                          system.debug('Name of my Cat'+name);

                          system.debug('Size of my Cat'+size);

                      }

                  }


                  If  change size is above 0









                  -------------------

                  Constructors in Apex

                  public class Cat 
                  {
                    private string name;
                      private integer size;
                      public Cat(string n, integer s) // Constructors with parameter
                      {
                          name=n;
                          size=s;
                      }
                     
                      public void display()
                      {
                          system.debug('Name of my Cat'+name);
                          system.debug('Size of my Cat'+size);
                      }
                  }


                  Yes, the constructor should always have the same name as the class.

                  Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class./ used to set the values of the instance variables when you creating objects 


                  public class Cat 

                  {

                    private string name;

                      private integer size;

                      public Cat(string n, integer s)  // Constructors with parameter

                      {

                          name=n;

                          size=s;

                      }

                      public Cat()  // Constructors without parameter

                      {

                          name='Teena';

                          size=10;

                      }

                      public void display()

                      {

                          system.debug('Name of my Cat'+name);

                          system.debug('Size of my Cat'+size);

                      }

                  }



                  ----------------------------

                  Inheritance in Apex

                  base class

                  Code:
                  public  virtual class vehicle {
                      public  void model()
                      {
                          system.debug('these is the vehicle model');
                      }
                      
                      public virtual void speed()
                      {
                          system.debug('this is speed for vehicle');
                      }
                  }

                  child class:

                  Code:
                  public class truck extends vehicle
                  {
                      public override void speed()
                      {
                          system.debug('these is the 50milesper/hr');
                      }
                  }



                  -------------------------------------------------



                  Collections in Apex (List, Set and Map)

                  Collections in Salesforce are various types that can contain numerous records. In other words, collections are groups of records . Collections have the ability to dynamically rise and shrink depending on the business needs. Collections in Apex can be lists, sets, or maps. There is no limit to the number of records that can be stored in a collection.

                  Salesforce has three types of collections:

                  • List collection
                  • Set collection
                  • Map collection

                  List Collection

                  A list can hold any type of data and is one of the most important types of collection. A list is an ordered collection of any data type such as primitive types, collections, sObjects, user-defined types, and built-in Apex types.

                  The following are the key features of a list collection in Salesforce:

                  • Duplicates and nulls are allowed in a list collection.
                  • “List” is the keyword to declare a list collection.
                  • In a list collection, the index position of the first entry is always zero (0).
                  • An Apex list collection has the ability to grow dynamically over time.
                  • In a list collection, the data type can be both primitive and non-primitive.
                  • The keyword followed by the data type has to be used within <> characters to define a list collection.

                  The syntax for a list is as follows:

                  List<datatype> listName = new List<datatype>();

                  List Class Salesforce:  All methods required for a list collection are stored in the Apex list class.

                  What are the Methods in List?

                  In order to use lists in programming to achieve certain functions, a few methods in Salesforce are available.

                  The following are the list-class methods in Salesforce:

                  • Add: The values or items are added to the list using the list.add() method.

                  The syntax to use the “add” method is as follows:

                  List name.add();

                  Here is an example:

                  List<String> names =new List<String>();
                  names.add('Ram');

                  Here, we are adding the “Ram” value to the list “names” using the method “add”.

                  • Clone: It is the method of making a new record by using the details of an existent one. Simply put, it is creating a duplicate record.

                  The syntax to use the “clone” method is as follows:

                  NewList= Old list name. clone();

                  Here is an example:

                  New Names= names.clone();

                  In the above example, a new list “New Names” is being created, which is the clone of the list “names”.

                  • Remove: It is the method of removing the specific value of the list.

                  The syntax to use the “remove” method is as follows:

                  List Name.remove(index);

                  Here is an example:

                  List<String> names = new List<String>();

                  names.add('Ram');

                  names.add('John');

                  names.add('Sony');

                  names.remove(2);

                  By using “remove” syntax in the above-mentioned example, the second position value, which is “Sony”, is being removed.

                  • Size: It is the method of finding the number of elements present in the list.

                  The syntax to use the “size” method is as follows:

                  Listname. size();

                  You have to write the list name of which you want to find the size.

                  • Equals: This is the method of defining whether the value is equal or not. If the list and the specific list are equal, true is returned; otherwise, false is returned.

                  The syntax to use the “equals” method is as follows:

                  result=Listone.equals(Listtwo);

                  Here, “List two” is being compared with “Listone”. If both elements are the same, it shows true; if both elements are not the same, then it shows false.

                  • Get: This is the method that helps to return or find out a value from a list.

                  The syntax to use the “get” method is as follows:

                  String getlist= list.get(index);

                  In this syntax, you have to replace “list” with “list name” and “index” with “index number”.

                  • Set: This is the method that is used to change the element or value of an index.

                  The syntax to use the “set” method is as follows:

                  list.set(index, value);

                  The value of the index, which is mentioned in the code, will be changed to the value that is present in the code.

                  For example, if you write names.set(1, Mark);

                  Here the value at the “index 1” of the list of “names” will be changed to “mark”.

                  • Clear: This is the method that removes or deletes an element in the list.

                  The syntax to use the “clear” method is as follows:

                  list.clear();

                  These are a few popular methods. We have discussed Apex collections in Salesforce; now, we are going to discuss the next type of collection.


                  Set Collection

                  Set is an unordered collection. It is a unique set of values that do not have any duplicates. If you want no duplicates in your collection, then you should opt for this collection.

                  The following are the key features of a set collection in Salesforce:

                  • Any data types, such as primitive data types and sObjects, are allowed in a set collection.
                  • A set collection does not have an index.
                  • A set collection does not contain any duplicates or null values.
                  • Set collections are not widely used in Salesforce Apex.
                  • Sets can hold collections that are nested inside of one another.
                  • You have to use the set keyword followed by the primitive data type name within <> characters to declare a set collection.

                  The syntax for a set is as follows:

                  Set<datatype> setName = new Set<datatype>();


                  What are the Methods in Set?

                  The following are the set-class methods in Salesforce:

                  • Add(): Use the add method to add an element in a set collection.

                  The syntax for the “add()” method is as follows:

                  setName.add();

                  Here is an example:

                  Set <string> CitiesSet = new set <string>();

                  CitiesSet.add(Newyork); // Newyork will be added in the cities set.

                  • Remove(): This method is used to remove element(s) from a set collection.

                  The syntax for the “remove()” method is as follows:

                  SetName.remove();

                  Here is an example:

                  Set <string> CitiesSet = new set <string>();

                  CitiesSet.remove(Newyork); //Newyork will be removed from the cities set.

                  • Size(): Same as in list collections, the size method can be used to find the count of elements in a set.

                  The syntax for the “size()” method is as follows:

                  Setname. size();

                  • Contain(): This method is used to determine whether or not an element exists in a set or not.

                  The syntax for the “contain()” method is as follows:

                  Setname.contain(element);

                  • isEmpty(): This method is used to find if the element is zero or not.

                  The syntax for the “isEmpty()” method is as follows:

                  Setname.isEmpty();

                  These are some of the methods in a set collection. There are many other methods available in a set collection such as clear(), clone(), hashcode(), equals(), and many more.

                  Map Collection

                  Map is a key-value pair that contains each value’s unique key. It is used when something needs to be located quickly.

                  The following are the key features of a map collection in Salesforce:

                  • Any data type can be used for both the key and the value in a map collection.
                  • In a map collection, the null value can be stored in a map key.
                  • The keys of type string are case-sensitive in a map collection.
                  • You have to use the map keyword followed by the key and value data types enclosed in <> to declare a map collection.

                  The syntax for a map is as follows:

                  Map<datatype_key,datatype_value> mapName = new Map<datatype_key,datatype_value>();

                  What are the Methods in Map?

                  The following are the map-class methods in Salesforce:

                  • put(key, value):  This method is used to add a value to a map collection.

                  The syntax for the “put(key, value)” method is as follows:

                  Map<integer, string> World Map = new Map <integer, string>();

                  World Map.put(1, ‘Australia’);

                  • get(key): This method helps to find the value of a key in a map collection.

                  The syntax for the “get(key)” is as follows:

                  Datatype_value = mapName.get(key);

                  • containskey(key): This method helps to declare that a map contains a specific key.

                  The syntax for the “containskey(key)” is as follows:

                  mapName.containskey(key);

                  • keySet(): This method is used to return a set containing all of a map’s keys.

                  The syntax for the “keySet()” is as follows:

                  Set<datatype_key> = mapName.keySet();

                  By now, you must have understood what exactly are collections in Salesforce with examples and how these collections can be used.



                                                  






                  Difference between set() and add() method of List



                  Sorting a list in apex salesforce








                  Set and Map in salesforce



                  Iterate over a set in salesforce: clear() method




                  Map in salesforce with example

















                  Types of Collections with Example (Summary)















                  Can you put a list inside of a Map?    --Yes  we can put the List in Map

                  Map<Id, List<Opportunity>> MapList=New Map<Id, List<Opportunity>>();


                  How do I convert a list to a map in Salesforce?



                  Convert like this :

                  List<Account> AccList = new List<Account>();
                  Map<Id,Account> AccMap = new Map<Id,Account>();
                  for(Account acc :AccList)
                  {
                  AccMap.put(acc.id,acc);
                  }



                  ===========================
                  SObjects in Salesforce

                  Every record in Salesforce is natively represented as an sObject in Apex


                  Each Salesforce record is represented as an sObject before it is inserted into Salesforce. Likewise, when persisted records are retrieved from Salesforce, they’re stored in an sObject variable.

                  Standard and custom object records in Salesforce map to their sObject types in Apex. Here are some common sObject type names in Apex used for standard objects.

                  • Account
                  • Contact
                  • Lead
                  • Opportunity

                  Create sObject Variables

                  Account acct = new Account(Name='Acme');

                  Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100);

                  Account acct = new Account();
                  acct.Name = 'Acme';
                  acct.Phone = '(415)555-1212';
                  acct.NumberOfEmployees = 100;




                  What is difference between SOQL and SOSL?

                  SOQL

                  SOSL

                  SOQL (Salesforce Object Query Language ) retrieves the records from the database by using “SELECT” keyword.

                  SOSL(Salesforce Object Search Language) retrieves the records from the database by using the “FIND” keyword.

                  By Using SOQL we can know in Which objects or fields the data resides.

                  By using SOSL, we don’t know in which object or field the data resides.

                  We can retrieve data from single object or from multiple objects that are related to each other.

                  We can retrieve multiple objects and field values efficiently when the objects may or may not be related to each other.

                  We can Query on only one table.

                  We can query on multiple tables.

                  Only one object can be searched at a time

                  Many objects can be searched at a time

                  Can query any type of field

                  Can query only on email, text or phone

                  Can be used in Class and Triggers

                  Can be used in Classes but not in Triggers

                  DML operation can be performed on query results

                  DML operation cannot be performed on search result

                  Returns Records

                  Returns Fields


                    How to write SOSL and SOQL queries in Salesforce?

                  1. In the Developer Console, open the Execute Anonymous window from the Debug menu.
                  2. Insert the below snippet in the window and click Execute.
                  // Add account and related contact
                  Account acct = new Account(
                      Name='SFDC Computing',
                      Phone='(415)555-1212',
                      NumberOfEmployees=50,
                      BillingCity='San Francisco');
                  insert acct;
                  // Once the account is inserted, the sObject will be 
                  // populated with an ID.
                  // Get this ID.
                  ID acctID = acct.ID;
                  // Add a contact to this account.
                  Contact con = new Contact(
                      FirstName='Carol',
                      LastName='Ruiz',
                      Phone='(415)555-1212',
                      Department='Wingo',
                      AccountId=acctID);
                  insert con;
                  // Add account with no contact
                  Account acct2 = new Account(
                      Name='The SFDC Query Man',
                      Phone='(310)555-1213',
                      NumberOfEmployees=50,
                      BillingCity='Los Angeles',
                      Description='Expert in wing technologies.');
                  insert acct2;

                  Use the Query Editor

                  The Developer Console provides the Query Editor console, which enables you to run SOSL queries and view results. The Query Editor provides a quick way to inspect the database. It is a good way to test your SOSL queries before adding them to your Apex code. When you use the Query Editor, you need to supply only the SOSL statement without the Apex code that surrounds it.

                  Let’s try running the following SOSL example:

                  1. In the Developer Console, click the Query Editor  tab.
                  2. Copy and paste the following into the first box under Query Editor, and then click Execute.
                  FIND {Wingo} IN ALL FIELDS RETURNING Account(Name), Contact(FirstName,LastName,Department)

                  What is  Aggregate Functions in SOQL?


                  Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query. You can use aggregate functions without using a GROUP BY clause. For example, you could use the AVG() aggregate function to find the average Amount for all your opportunities.

                  AggregateResult[] groupedResults
                    = [SELECT AVG(Amount)aver FROM Opportunity];
                  Object avgAmount = groupedResults[0].get('aver');


                  So the functions count(fieldname), count_distinct(), sum(), avg(), min() and max() return an AggregateResult object (if one row is returned from the query) or a List of AggregateResult objects (if multiple rows are returned from the query). You access values in the AggregateResult object much like a map calling a “get” method with the name of the column. In the example below you can see how you can access a column name (leadsource), alias (total) and an unnamed column (expr0). If you have multiple unnamed columns you reference in the order called with expr0, expr1, expr2, etc. 

                  List<aggregateResult> results = [select leadsource, count(name) total,
                   count(state) from lead group by leadsource ]; 
                  for (AggregateResult ar : results)
                   System.debug(ar.get('leadsource')+'-'+ar.get('total')+'-'+ar.get('expr0')); 

                  The AggregateResult returns the value as an object. So for some operations you will need to cast they value to assign them appropriately.

                  Set<id> accountIds = new Set<id>();
                  for (AggregateResult results : [select accountId from contact group by accountId])
                    accountIds.add((ID)results.get('accountId'));


                  One this to be aware of is that the count() function does not return an AggregateResult object. The resulting query result size field returns the number of rows: 

                  Integer rows = [select count() from contact];
                  System.debug('rows: ' + rows);

                  You can also do some cool things like embed the SOQL right in your expression:

                  if ([select count() from contact where email = null] > 0) {
                    // do some sort of processing...
                  }


                  How to get Maps from SOQL Query in salesforce?

                  As we all know, Apex code has limitation of  Number of code statements that can be executed. While writing Apex code, we should take care of number of code statement that are  executed to avoid governor limits. It is useful to understand how to reduce the number of executed code statements so that we can stay within the governor limits.

                  Normally we get list of records in a SOQL query.Sometime we also need set of id’s or map of record id’s and record or list of record id’s.

                  Apes code for above requirement will be as below:



                  //Creating List of all account Ids
                  List<id> accIdsList = new List<id>() ;

                  //Creating set of all account Ids
                  Set<id> accIdsSet = new Set<id>() ;

                  //Creating Map with account id as key and account record as value
                  Map<Id,Account> accountIdObjMap = new Map<Id,Account>();

                  //Fetching all accounts
                  List<account> accList = [select Id,name,site,rating,AccountNumber from account limit 50000] ;

                  //Fetching Account ids
                  for(Account acc : accList){
                      accIdsSet.add(acc.id);
                      accIdsList.add(acc.id);
                      accountIdObjMap.put(acc.id,acc);
                  }



                  In the code above, if there are large number of records(say 50000) then for loop will be executed 50000  times and also every line in for loop will be executed 50000 times. We can avoid this unnecessary for loop by using good SOQL query which will return map instead of list. After that we can easily get list of accounts or set of account Id’s or List of account Id’s using methods.

                  New Apex Code will be as below:


                  //Creating List of all account Ids
                  List<id> accIdsList = new List<id>() ;

                  //Creating set of all account Ids
                  Set<id> accIdsSet = new Set<id>() ;

                  //Fetching all accounts
                  List<account> accList = new List<Account>();

                  //Creating Map with account id as key and account record as value
                  Map<Id,Account> accountIdObjMap = new Map<Id,Account>([select Id,name,site,rating,AccountNumber from account limit 50000]);

                  //getting list of account using map.values method
                  accList = accountIdObjMap.values();

                  //getting set of account Id's using map.keySet method
                  accIdsSet = accountIdObjMap.keySet();

                  //getting list of account Id's using list.addAll method
                  accIdsList.addAll(accIdsSet);


                  SOQL Query Examples
                  A SOQL query is enclosed between square brackets.

                  sObject s = [SELECT Id, Name FROM Merchandise__c WHERE Name='Pencils'];

                  A SOQL statement is centered on a single database object, specifying one or more fields to retrieve from it.The fields to select are separated by commas.

                  Simple SOQL Statement

                  SELECT Id, Name FROM Account

                  Filtering Records

                  SOQL supports filter conditions to reduce the number of records returned.A filter condition
                  consists of a field name to filter, an operator, and a literal value.
                  Valid operators are

                  > (greater than),
                  < (less than),
                  >= (greater than or equal to),
                  <= (less than or equal to),
                  = (equal to),
                  != (not equal to),
                  IN and NOT IN (matches a list of literal values, and supports semi-joins and anti-joins), and INCLUDES and EXCLUDES (match against multi-select picklist values).

                  On String fields the LIKE operator is also available,
                  which applies a pattern to filter records.The pattern uses the % wildcard to match zero or
                  more characters, _ to match one character, and the \ character to escape the % and _
                  wildcards, treating them as regular characters.

                  EX: -

                  SELECT Name
                  FROM Account
                  WHERE AnnualRevenue > 100000000
                  AND Type = 'Customer - Direct'
                  AND LastModifiedDate = THIS_YEAR

                  SOQL Statement with Record Limit

                  SELECT Name, Type
                  FROM Account
                  WHERE LastModifiedDate = TODAY
                  LIMIT 10

                  Sorting Query Results

                  Results of a query can be sorted by up to 32 fields in ascending (ASC, the default) or descending (DESC) order. Sorting is not case-sensitive, and nulls appear first unless otherwise specified (NULLS LAST).Multi-select picklists, long text areas, and reference type fields cannot be used as sort fields.

                  EX: -

                  SELECT Name, Type, AnnualRevenue
                  FROM Account
                  ORDER BY Type, LastModifiedDate DESC

                  Querying Multiple Objects

                  The result of a SOQL query can be a simple list of records containing rows and columns or hierarchies of records containing data from multiple, related objects. Relationships between objects are navigated implicitly from the database structure.

                  The two ways to navigate object relationships in SOQL are child-to-parent and parent-to-child.

                  SOQL with Child-to-Parent Relationship
                  EX: -

                  SELECT Name, Contact__r.MailingCity, Contact__r.CreatedBy.Name
                  FROM Resource__c
                  WHERE Contact__r.MailingState = 'IL'

                  At most, five levels of parent objects can be referenced in a single child-to-parent query, and the query cannot reference more than 25 relationships in total.

                  SOQL with Parent-to-Child Relationship

                  The second form of relationship query is the parent-to-child query.

                  EX: -

                  SELECT Id, Name,
                  (SELECT Total_Hours__c
                  FROM Timecards__r
                  WHERE Week_Ending__c = THIS_MONTH)
                  FROM Resource__c

                  Note: A parent-to-child query cannot reference more than twenty child objects.

                  SOQL Query in Apex Using SOQL For Loop

                  Decimal totalHours = 0;
                  for (Proj__c project : [ SELECT Total_Billable_Hours_Invoiced__c FROM Proj__c
                  WHERE Start_Date__c = THIS_YEAR ]) {
                    totalHours += project.Total_Billable_Hours_Invoiced__c;
                  }


                  if you want more details Click on below


                  What are Salesforce Email Services?

                  Email services are automating the messaging process in salesforce that offers secure and robust functionality to send emails from the Salesforce. In this Salesforce Email Tutorial, we will discuss email services in Salesforce, Salesforce inbound email handler, Salesforce email integration, inbound email service in salesforce, and outbound email service in Salesforce. 

                  Types of Email Services in Salesforce

                  Email messages are a more robust and powerful message exchange scheme in Salesforce. When you have to send or receive some email from external systems then we can use email services in Salesforce. There are two most common types of Salesforce email services as given below and we will discuss each of them in detail in future sections.

                  • Inbound email service in salesforce
                  • Outbound email service in salesforce

                  Moving ahead, let us discuss what is inbound email service in Salesforce.

                  Inbound Email Services in Salesforce

                  You can use Apex to receive and process email and attachments from the external system to Salesforce. The email is received by the Apex email service and processed by Apex classes that utilize the Inbound Email object. Apex Salesforce email services create an Inbound Email object that contains the contents and attachments of that email. You can use Apex classes to implement the Messaging, Inbound Email Handler Salesforce interface to handle an inbound Salesforce email message. You can access an Inbound Salesforce Email object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many functions.

                  Below are predefined classes

                  • Inbound Email Handler
                  • Inbound Email Binary Attachments
                  • Inbound Email Inbound Envelope
                  • Inbound Email Result.

                  Moving ahead, let us discuss the main methods and properties in Inbound Salesforce Email.

                  Methods/Properties in Inbound Salesforce Email

                  Here is a complete list of methods used in inbound Salesforce Email.

                  • Binary Attachments: A list of binary attachments received with the email if any.
                  • CC Addresses: A list of carbon copy (CC) addresses if any.
                  • From Address: The Salesforce email address that appears in the From field.
                  • From Name: The name that appears in the From field, if any.
                  • Headers: A list of the RFC 2822 headers in the email.
                  • HTML Body: The HTML version of the email, if specified by the sender.
                  • HTML Body Is Truncated: Indicates whether the HTML body text is truncated (true) or not (false.)
                  • In Reply To: The In-Reply-To field of the incoming email. Identifies the email or emails to which this one is a reply (parent emails). It Contains the parent email or emails' message-IDs.
                  • Message-Id: The Message-ID—the incoming email's unique identifier.
                  • Plain Text Body: The plain text version of the email, if specified by the sender.
                  • Plain Text Body Is Truncated: Indicates whether the plain body text is truncated (true) or not (false.)
                  • Reply To: The email address that appears in the reply-to header.
                  • Subject: The subject line of the email, if any.
                  • Text Attachments: A list of text attachments received the email if any.
                  • To Addresses: The email address that appears in the To

                  Inbound Envelope Properties

                  The following are properties for Inbound Envelope.

                  • From Address The name that appears in the From field of the envelope, if any.
                  • To Address The name that appears in the Tofield of the envelope, if any.

                  Messaging Inbound Envelope:

                  This object of this class store the information of the envelope (From address and to address) associated with inbound email.


                  Messaging. Inbound Email Result:

                  The Inbound Email Result used to return the result of the email service. To access email services in Salesforce we need to activate email service

                  How to Configure inbound email services in Salesforce?

                  Navigation Setup ->Build->Develop -> Email Services->New Email service

                  1. Give a name for Email Service Name.
                  2. For Apex Class, specify the Apex class you just built
                  3. Define the attachment type.
                  4. Mention from where we want to receives an email.
                  5. Select active.
                  6. You can leave the rest of the fields at their default values for starters
                  7. Click on save.

                  Outbound Email Services in Salesforce.

                  You can use Apex to send individual and mass email. The email can include all standard email attributes (such as subject line and blind carbon copy address), use Salesforce email templates, and be in plain text or HTML format, or those generated by Visualforce.

                  Visualforce email templates cannot be used for mass email.

                  To send individual and mass email with Apex, use the following classes:

                  SingleEmailMessage
                   Instantiates an email object used for sending a single email message. The syntax is:
                  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                  SingleEmailMessage Methods

                  Single Email message consists of nearly 19 methods that can be used in Email messages in Salesforce.

                  SetBccAddresses(bccAddresses)

                  This method will set Bcc Address to the whom the email should be sent. We can set up to 25 email addresses.

                  String[] toBccAddresses = new String[] {'salesforcehandbook@gmail.com', example@gmail.com};
                  mail.setBccAddress(tobccaddress);

                  setCcAddresses(ccAddresses)

                  This method will set CcAddress to whom the mail should be sent. We can set utp 25 email address.

                  String[] toCcAddresses = new String[] {'salesforcehandbook@gmail.com', example@gmail.com};
                  mail.setCcAddress(toccaddress);

                  setToaddress()

                  This method will set the address, we can set up to 100 addresses.

                  String[] toAddress = new String[] {'salesforcehandbook@gmail.com', example@gmail.com};
                  mail.setToAddress(toaddress);

                  setSubject(string)

                  setSubject( ) method will set the subject of mail.

                  myemail.setSubject('salesforcehandbook');

                  setPlainTextBody()

                  setPlainTextBody() will set the main body of the mail.

                  myemail.setPlainTextBody('Welcome to salesforcehandbook');

                  setHtmlBody(htmlBody)

                  setHtmlBody( ) will set the main body of the mail.

                  myemail.setHtmlBody('<h1> Subscribe to salesforcehandbook.com'</h1>);

                  MassEmailMessage
                  Instantiates an email object used for sending a mass email message. The syntax is:
                  Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();


                  Messaging.MassEmailMessage

                  Messaging.MassEmailMessage class all the methods defined in the Email class and also Email base class methods.

                  Signature : public MassEmailMessage()

                  Mass Email Message Methods

                  • setDescription(description) : This will give the description about the mail.
                  • setTargetObjectIds(targetObjectIds) : We can add upto 250 IDs per email. If you specify a value for the target Object Id’s field optionally specify a WhatID’s as well.
                  • setWhatIds(whatIds) : This values can be . any one of the following contact, case, opportunity and product.

                  Syntax

                  Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();


                  public class EmailClassSend {
                      public static void sendSingleMail()
                      {
                      Messaging.SingleEmailMessage semail=new Messaging.SingleEmailMessage();
                      String[] sendingto=new String[]{'venkat.goshika@gmail.com'};
                          semail.setToAdresses(sendingto);
                      semail.setSubject('Single Email Messaging Test');
                      semail.setPlainTextBody('Hello How are you msg from Apex');
                      Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
                  }
                  }


                  Note:
                  • The email is not sent until the Apex transaction is committed.
                  • The email address of the user calling the sendEmail method is inserted in the From Address field of the email header. All email that is returned, bounced, or received out-of-office replies goes to the user calling the method.
                  • Maximum of 10 sendEmail methods per transaction. Use the Limits methods to verify the number of sendEmail methods in a transaction.
                  • Single email messages sent with the sendEmail method count against the sending organization's daily single email limit. When this limit is reached, calls to the sendEmail method using SingleEmailMessage are rejected, and the user receives a SINGLE_EMAIL_LIMIT_EXCEEDED error code. However, single emails sent through the application are allowed.
                  • Mass email messages sent with the sendEmail method count against the sending organization's daily mass email limit. When this limit is reached, calls to the sendEmail method using MassEmailMessage are rejected, and the user receives a MASS_MAIL_LIMIT_EXCEEDED error code.
                  • Any error returned in the SendEmailResult object indicates that no email was sent.
                  Sending Single Email From Apex:
                  public class ContactOutBoundEmailService { //Constructor do nothing. public ContactOutBoundEmailService(){ } public void createContactAndSendEmail(){ Contact contObj = new Contact(); contObj.firstName = 'Venkanna'; contObj.lastName = 'Goshika'; contObj.email = 'venkat.goshika@gmail.com'; contObj.Phone = '919916145532'; contObj.description = 'This is Test contact created for outboundemailservice.'; insert contObj; system.debug('==>created Contact is==>'+contObj.id); // First, reserve email capacity for the current Apex transaction to ensure // that we won't exceed our daily email limits when sending email after // the current transaction is committed. Messaging.reserveSingleEmailCapacity(2); // Processes and actions involved in the Apex transaction occur next, // which conclude with sending a single email. // Now create a new single email message object // that will send out a single email to the addresses in the To, CC & BCC list. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // Strings to hold the email addresses to which you are sending the email. String[] toAddresses = new String[] {contObj.email}; String[] ccAddresses = new String[] {contObj.email}; // Assign the addresses for the To and CC lists to the mail object. mail.setToAddresses(toAddresses); mail.setCcAddresses(ccAddresses); // Specify the address used when the recipients reply to the email. mail.setReplyTo('venkat.goshika@gmail.com'); // Specify the name used as the display name. mail.setSenderDisplayName('Salesforce Support'); // Specify the subject line for your email address. mail.setSubject('New Contact Created : ' + contObj.Id); // Set to True if you want to BCC yourself on the email. mail.setBccSender(false); // Optionally append the salesforce.com email signature to the email. // The email address of the user executing the Apex Code will be used. mail.setUseSignature(true); // Specify the text content of the email. mail.setPlainTextBody('Your Contact: ' + contObj.Id +' has been created.'); mail.setHtmlBody('Your Contact:<b> ' + contObj.Id +' </b>has been created.<p>'+ 'To view your Contact <a href=https://ap1.salesforce.com/'+contObj.Id+'>click here.</a>'); // Send the email you have created. Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }
                  Mass Email Message:
                  public class ContactMassOutBoundEmailService { List<Id> contactList = new List<Id>(); List<ID> whatIds = new List<ID>(); //Constructor do nothing. public ContactMassOutBoundEmailService(){ } public void createContactAndSendMassEmail(){ Contact contObj = new Contact(); contObj.firstName = 'Venkanna'; contObj.lastName = 'Goshika'; contObj.email = 'venkat.goshika@gmail.com'; contObj.Phone = '919848230288'; contObj.description = 'This is Test contact created for outboundemailservice.'; insert contObj; contactList.add(contObj.id); system.debug('==>created Contact is==>'+contObj.id); if(contactList !=null && contactList.size()>0){ Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage(); mail.setTargetObjectIds(contactList); //Get the email template id to send the html email message. mail.setTemplateId([SELECT id FROM EmailTemplate WHERE Name = 'CreateContactAndSendMassEmail'].id); mail.saveAsActivity = false; Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail }); } }  

                  Governance Salesforce email limits

                  Salesforce has a limit on the number of email messages that you can process in the whole day. If this limit exceeds then the remaining message will jump to the next day for processing automatically. The execution depends on how you configure the failure response setting for each email message either inbound or outbound. Salesforce email limits are calculated by multiplying the total number of licenses to 1000 up to a daily maximum limit of 1,000,000.

                  When you are sure of Salesforce email limits, let us discuss how to create email services in salesforce.

                  How to create Salesforce Email Services?

                  To use email services, go to the setup option then email services option.

                  • Click on email service options and create a new email message.
                  •  Now create an apex class using an apex inbound email handler.
                  •  Check the active checkbox.
                  • Now, you can configure the email service to send or receive messages from limited sender or receivers. If you don’t configure this field then leave it empty.
                  • Configure the failure response settings.
                  • In the end, save the changes you made to particular email service.

                  Once the email service is created, create an email address for the service from the bottom of the page. An email service can have multiple email addresses attached to it as needed.

                  ============= ---------------------------------------------------------------------------=============

                  Exceptions In Apex

                  In apex, exceptions are used to note errors and other events that have disrupted the normal flow of code execution. Try catch code blocks can be used to handle exceptions that may occur in the code.

                  There are three statements that can be used trycatch and finally.

                  • The try statement identifies the block of code that an exception may occur in.
                  • The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can have zero catch statements or more catch statements. Every catch statement must have a unique exception type. When one exception type is caught, the remaining catch blocks will not be executed.
                  • The finally statement identifies a block of code that is guaranteed to be executed, this allows you to use it to clean up your code. A try statement can have a max of one finally statement. Code in the finally block will always execute regardless of whether an exception was thrown or the type of exception that was thrown. This is why the finally statement can be used to clean up your code Eg. freeing up resources.

                  Apex Try Catch block Syntax


                  public class Example { public void exampleMethod(){ try { //Try block of code //Perform logic here } catch (exceptionType variableName) { // First catch block for specific exception // It checks Exception in the order they are in the code // Exception must be the last Catch as its a general exception //Perform logic to handle exception } catch (Exception e) { // You can have Optional additional catch statement for other exception types. // Note that the general exception type, 'Exception' // Exception must be the last catch block when it is used. //Perform logic to handle exception } finally { // Finally block. // Must have a finally statement or at least one catch statement //Perform logic that must happen regardless of if exception occurs } } }

                  ----
                  public class Example { public static void exampleMethod(){ try { //This will cause a query exception to fire as more than one account will be returned //We can then see our debug statement for queries in the debug logs Account accountsToUpdate = [SELECT Id, Rating FROM Account]; //This does not get executed as the line above causes an exception System.debug('Line of code after exception'); }catch (QueryException e) { //If a query exception occurs it will go here System.debug('Query Exception hit'); }catch(DmlException e){ //If a DML exception occurs it will go to this statement System.debug('DmlException hit'); }catch (Exception e) { //Any other exceptions that occur will go here System.debug('Exception hit'); } finally { //Clean up } } }

                      public static void exampleMethod(){

                          try {

                              //This will cause a query exception to fire as more than one account will be returned

                              //We can then see our debug statement for queries in the debug logs

                              Account accountsToUpdate = [SELECT Id, Rating FROM Account];

                                          

                              //This does not get executed as the line above causes an exception

                              System.debug('Line of code after exception');

                          }catch (QueryException e) {

                                //If a query exception occurs it will go here

                                System.debug('Query Exception hit');

                          }catch(DmlException e){

                                    //If a DML exception occurs it will go to this statement

                                    System.debug('DmlException hit');

                          }catch (Exception e) {

                                    //Any other exceptions that occur will go here

                                System.debug('Exception hit');

                          } finally {

                                     //Clean up

                          }

                      }

                  }

                  Tip : 

                  Any code in the try catch block that is after where the exception occurred is skipped and will not be executed.

                  Always have the generic exception as the last catch statement otherwise, the other catch statements won't be reached as the generic exception will always run first before the other catch statements.

                  The above code highlights how we can have multiple catch statements if we want to handle some exceptions differently.

                  If we don't want to handle some exceptions differently and we do not have any code that must be executed regardless of if there's an exception. We can just have the general exception catch statement.

                  public class Example {

                   

                      public static void exampleMethod(){

                          try {

                                  //This will cause a query exception to fire as more than one account will be returned

                                  //We can then see our debug statement for queries in the debug logs

                                       Account accountsToUpdate = [SELECT Id, Rating FROM Account];

                   

                          }catch (Exception e) {

                                      //Handle any exceptions that occur

                                      System.debug('Exception hit');

                          }

                      }

                  }

                  Note : When writing a try statement, there must be at least one catch block or a finally block with it. You cannot have a try block on its own. Salesforce will prompt you with an error if the try block is on its own

                  If we try to save the code below, we will get an error.

                  public class tryCatch {

                       public void exampleMethod(){

                           try {

                               //Try block of code

                               //Perform logic here

                              

                           }

                       }

                  }


                  Salesforce gives us the error message Try block must have at least one catch block or a finally block


                   







                  1. DMLException:

                  DML Exceptions are exceptions that occur whenever a DML operation fails. This may happen due to many reasons, the most common one is inserting a record without a required field.

                  Ex: try

                  {

                      Position__c pos = new Position__c();

                      insert pos;

                  catch(DmlException e)

                  {

                  System.debug(‘The following exception has occurred: ‘ + e.getMessage()); 

                  }

                  2. ListException:

                  ListException catches any type of run time error with a list. This list can be of any data type such as integer, string, or sObject.

                  Ex: try

                  {

                      List<String> stringList = new List<String>();

                      stringList.add(‘Bhavna’);

                      // This list contains only one element,

                      // but we will attempt to access the second element

                      // from this zero-based list.

                      String str1 = stringList[0]; //this will execute fine

                      String str2 = stringList[1]; // Causes a ListException

                  }

                  catch(ListException le)

                  {

                  System.debug(‘The following exception has occurred: ‘ + le.getMessage());

                  }

                  3. NullPointerException:

                  NullPointer Exception catches exceptions that occur when we try to reference a null variable. Use this exception whenever you are referencing a variable that might turn out to be null.

                  Ex: try

                  {

                  String stringVariable;

                  Boolean boolVariable = stringVariable.contains(‘John’);

                  // Causes a NullPointerException

                  }

                  catch(NullPointerException npe)

                  {

                  System.debug(‘The following exception has occurred: ‘ + npe.getMessage());

                  }

                  4. QueryException:

                  QueryException catches any run time errors with SOQL queries. QueryException occurs when there is a problem in SOQL queries such as assigning a query that returns no records or more than one record to a single sObject variable.

                  Ex: try {

                      // This statement doesn’t cause an exception,

                      // if we don’t have a problem in SOQL Queries.

                      // The list will just be empty.

                  List<Position__c> positionList = [SELECT Name FROM Position__c WHERE Name=’Salesforce Developer’];

                      // positionList.size() is 0 

                      System.debug(positionList.size());

                  // However, this statement causes a QueryException because 

                  // we’re assiging the query result to a Position sObject varaible

                         // but no Position record is found

                  Position__c pos = [SELECT Name FROM Position__c WHERE Name=’Salesforce Developer’ LIMIT 1];

                  }

                  catch(QueryException ge) {

                  System.debug(‘The following exception has occurred: ‘ + ge.getMessage());    

                  }

                  5. Generic Exception:

                  This exception type can catch any type of exception; that’s why it’s called generic Exception type. This is used when you are not sure which exception type to use and what exception might occur in the code.

                  Ex: try {

                  List<Position__c> positionList = [SELECT Name FROM Position__c WHERE Name=’Salesforce Developer’];

                       // positionList.size() is 0 

                       System.debug(positionList.size());

                  Position__c pos = [SELECT Name FROM Position__c WHERE Name=’Salesforce Developer’ LIMIT 1];

                  } catch(Exception ex) {

                  System.debug(‘The following exception has occurred: ‘ + ex.getMessage());    

                  }

                  Common Exception Methods:

                  All Exception types are Exception classes and these classes have methods that can provide a lot of information about the exception and error that occurred.

                  1.   getTypeName(): Returns the type of exception, such as DmlException, ListException, and QueryException. 

                  2.   getMessage(): Returns the error message and displays for the user.

                  3.   getCause(): Returns the cause of the exception as an exception object.

                  4.   getLineNumber(): Returns the line number from where the exception was thrown.

                  5.   getStackTraceString():Returns the stack trace as a string. 


                  Ex: try {

                      Position__c pos = new Position();

                      // Causes an QueryException because

                      // we are inserting record without required fields

                      insert pos;

                  catch(Exception e) 

                  {

                      System.debug(‘Exception type caught: ‘ + e.getTypeName());    

                      System.debug(‘Message: ‘ + e.getMessage());    

                      System.debug(‘Cause: ‘ + e.getCause());    // returns null

                      System.debug(‘Line number: ‘ + e.getLineNumber());

                  }

                  USER_DEBUG|[6]|DEBUG|Exception type caught: System.QueryException

                  USER_DEBUG|[7]|DEBUG|Message: List has no rows for assignment to SObject

                  USER_DEBUG|[8]|DEBUG|Cause: null

                  USER_DEBUG|[9]|DEBUG|Line number: 2

                  USER_DEBUG|[10]|DEBUG|Stack trace: AnonymousBlock: line 2, column 1

                   

                  When an Exception occurs ?

                  • When an exception occurs, code execution halts.
                  • Any DML operations that were processed before the exception are rolled back and aren’t committed to the database.
                  • Exceptions get logged in debug logs.
                  • For unhandled exceptions that is exceptions that the code doesn’t catch, salesforce sends an email that includes the exception information. The end user sees an error message in the Salesforce user interface.


                  Why is it important?

                  If exceptions are not handled properly then user experience is poor especially when Salesforce Built-In exception are thrown as the error message appears at the top of the page which users may not understand.

                  Example:

                  apex try catch

                  What are the different types of exception?

                  A developer may choose to use the built-in exceptions provided by Salesforce for majority of the executions that can occur or create their own specific exceptions that fit the use case of the logic.

                  Built-In Exceptions

                  Apex provides a number of built-in exception types that the runtime engine throws if errors are encountered during execution.

                  1. DMLException: This exception occurs when an error occurs when trying to insert, update or delete a record in Salesforce.
                  2. ListException:  This exception occurs when there is an issue with a list of records. Either when a list is empty and is being referenced without checking first if it is empty or if list has n number of records and your code is looking for n+1th record.
                  3. NullPointerException: This exception occurs when a variable contains no value and is being referenced in code.
                  4. QueryException: This exception occurs when a SOQL query is written poorly and the returning values are not handled properly.
                  5. sObjectException: This exception occurs when the logic in the try catch is attempting to update a field that is not queried first.
                  6. Exception: This is a catch all exception type where if you don’t specify any of the above then this will still catch all exceptions above gracefully.

                  Example:

                  try {
                      String s;
                      Boolean b = s.contains('abc'); // Causes a NullPointerException
                  } catch(DmlException e) {
                      System.debug('DmlException caught: ' + e.getMessage()); 
                  } catch(SObjectException e) {
                      System.debug('SObjectException caught: ' + e.getMessage()); 
                  } catch(Exception e) {
                     System.debug('Exception caught: ' + e.getMessage()); 
                  }

                  Custom Exceptions

                  The THROW statement only works when using a custom exception and can only be written within the TRY block.

                  To create your custom exception class, extend the built-in Exception class and make sure your class name ends with the word Exception, such as “MyException” or “PurchaseException”. All exception classes extend the system-defined base class Exception, and therefore, inherits all common Exception methods.

                  public class ExceptionExample {
                       public virtual class BaseException extends Exception {}
                       public class OtherException extends BaseException {}
                  
                       public static void testExtendedException() {
                            try {
                                 Integer i=0;
                                 // Your code here
                                 if (i < 5) throw new OtherException('This is bad');
                          } catch (BaseException e) { 
                               // This catches the OtherException
                              System.debug(e.getMessage());
                         } 
                     }
                  }

                  What can you print in the debug log?

                  There are multiple exception methods available that can be used to find the root cause of a problem. Here are descriptions of some useful methods:

                  • getCause: Returns the cause of the exception as an exception object.
                  • getLineNumber: Returns the line number from where the exception was thrown.
                  • getMessage: Returns the error message that displays for the user.
                  • getStackTraceString: Returns the stack trace of a thrown exception as a string.
                  • getTypeName: Returns the type of exception, such as DmlException, ListException, and so on.

                  Example: To find out what some of the common methods return, try running this example.

                  try {
                      Case c = new Case();
                      c.Subject = 'This is a new Case.';
                      insert c;
                  } catch(Exception e) {
                     System.debug('Exception type caught: ' + e.getTypeName()); 
                     System.debug('Message: ' + e.getMessage()); 
                     System.debug('Cause: ' + e.getCause()); // returns null
                     System.debug('Line number: ' + e.getLineNumber()); 
                     System.debug('Stack trace: ' + e.getStackTraceString()); 
                  }

                  Conclusion

                  It is considered as a best practice in the world of programming to wrap all executions in a try catch statement to ensure user experience is seamless even when code fails to run successfully.


                  No comments: