You are on page 1of 25

Force.

com Platform:
===================
Salesforce Offers:
1. SAAS: Salesforce CRM

Limits:
1. We Can't arrange the fields in more than 2 columns
inside a
section.

2. We can't Change the Color, Size, Font, Style of the


Standard Page Layouts.

3. We don't have the De-Duplication mechanism.

4. We can't Customize the Tab HomePage given by Salesforce.

5. Through Workflow Rules, we can't add any attachments to


be get send to the customer along with the email.

6. We can't update more than 40 fields through Workflow


rules.

7. We can't perform the Cross-Object field updates in


Lookup Relationships.

8. We can implement the Custom Roll-up Summary


functionalities between Lookup Relationships

2. PAAS: Force.com Platform:


|
--> Cloud Platform to be get used to customize the
Application functionalities.

1. We can Customize the Existing Applications.

2. We can Leverage / Extend the Application


features, by adding the additional Enhancements.

3. We can Develop the Custom Applications like


"Banking, Finance, Insurance, HealthCare, Pharma, Manufacturing, Consulting,...etc.

4. We can integrate the Salesforce Application


with any External System.

2 Types of Customizations.

1. Declarative Customizations: (Without Coding)

Benefits:
1. No need to have the Technical Skills.
2. Easy to implement
3. Each feature will be implemented by using "Mouse
Clicks".
4. It will save the Time.
5. Save the Budget.

2. Programmatic Customizations: (With Coding)


|
--> Force.com Platform

Benefits:
1. We can implement Complex Functionalities.
2. We can design the Customized User Interfaces with
attractive Look and Feel.
3. We can implement the Complex Business Logic based
on the application requirement.

Force.com Platform
|
--> 2 Programming Languages.

1. Apex Programming:
Used to implement the Custom
Business Logic.

2. Visualforce Programming:
Visualforce is a Web Development
Framework, to be used to design the Attractive and Dynamic user interfaces with
"Rich Look and Feel".

Apex Programming:
=================
Apex is a Cloud Based Programming Language, which doesn't requires any
installations.

Apex is an Object Oriented Programming Language, Where each business logic will be
available in the form of "Classes and Objects".

Through Apex Programming, we can implement the Complex Validations, Complex


Business Logics and Complex Transactional flows.

By using Apex Programming language, we can implement the Custom Business Logics.

Apex is Not a Case-Sensitive Programming. We can write the code by using any
character case.

Apex is tightly integrated with the Salesforce Objects. Hence we can perform all
the DML operations on the Salesforce objects.
(i.e. We can perform INSERT, UPDATE, DELETE, UNDELETE, UPSERT and MERGE operations
on the Database object records)

By using Apex programming, we can fetch the records from one or more objects with
the help of a Query Language called as "SOQL Queries".
(SOQL --> Salesforce Object Query Language)

By using Apex programming, we can search for the required content in one or more
objects at a time with the help of "SOSL Queries".
(SOSL --> Salesforce Object Search Language)

By using Apex programming, we can process millions of records with the help of
"Batch Programming and Schedule Programming".

By using Apex programming, we can integrate the Salesforce Applications with any
external system with the help of "REST API and SOAP API".
(API ---> Application Programming Interface)
(REST --> Representational State Transfer)
(SOAP --> Simple Object Access Protocol)

Each Statement in apex programming should be ends with a Semicolon.

Note:
Each Apex Programming Code will get compiled by using "Apex Compiler" and
will get executed by using a Runtime Engine called as "Apex Runtime".

Each Apex Class will get stored inside the "ApexClass" object.

Each Apex class code will get stored inside a file with the extension ".apxc". And
Each Apex Trigger will get stored inside the file with the extension ".apxt".

Apex Programming Execution LifeCycle:


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

Debug Log File:


Setup --> Monitor --> Logs --> Debug Logs

Developer Console
|
--> TabBar
|
--> Logs Tab.

Data Types:
-----------
DataTypes describes the below 2 things

1. What Type of Data the variable can hold.


2. How much memory needs to be get required.

Apex provides 2 Types of DataTypes.

1. Primitive DataTypes:
It contains the Fundamental / Basic DataTypes provided by apex
programming.

Ex:
Integer, Decimal, Double, Long, String, Boolean, Date,
Time, DateTime, ID, Blob, Object.

Integer:
--------
It allows us to store the Numerical values without any
decimal points.

Ex: 10, 4500000, 3000,456,...etc.

Each Integer value will occupy 4-Bytes of memory.

Range: -2^31 to +2^31-1

Note:
Each Number field, Percent field, and currency field
will reference the "Integer DataType".
Boolean:
--------
It allows us to store TRUE / FALSE value.

Note:
Each CheckBox field will reference the "Boolean"
DataType.

ID:
---
It will store either 15 / 18 characters Record ID.

Note:
Each ID Field, Lookup Relationship, Master-Detail
Relationship, Hierarchical Relationship, and External Object Lookup Relationship
fields are referencing the "ID DataType".

String:
-------
Allows us to store a collection of characters. String
values should be enclosed with a Single Quote.

Ex:
'Ramesh', 'Pawan Kumar', 'M'

Note:
Auto Number,Phone, Email, URL, Text, Text Area, Text
Area Long, Text Area Rich, Picklist, Picklist-MaultiSelect, Text Encrypted, Geo
Location, Formula,..etc.

Date:
-----
Allows us to store the Date Value.

Note:
Each Date Field will reference the Date DataType.

Time:
-----
Allows us to store the Time Value either in 12 / 24 hours
format.

Note:
Each Time Field will reference the Time DataType.

DateTime:
---------
Allows us to store the DateTime stamp Value.

Note:
Each DateTime Field will reference the DateTime
DataType.

Long:
-----
It allows us to store the Larger Integer values without any
decimal points.

We can store the values between the range -2^63 to +2^63-1.


Each Long DataType variable will occupy 8-Bytes of memory.

Decimal:
--------
It allows us to store the Numerical values including the
decimal digits inside the variable.

Ex:
150.50
175.20

Note:
Each Currency field will reference the Decimal
Datatype by default.

Double:
-------
It allows us to store the Numerical values with more number
of decimal digits inside the variable

Ex:
10 / 3 = 3.3333333333333
3.1412

Blob: (Binary Large Objects)


-----
This datatype allows us to store the Binary content of
Images, Pictures, Audio Files, Video Files, Attachments, Documents,...etc.

Note:
Each Document object will reference the Blob
DataType.

Object:
-------
It allows us to store any of the value inside the variable.
It is a Generic DataType.

Note: Object is the "Base Class" for the Apex Programming.

2. SObject DataTypes (SObject --> Salesforce Object)


Used to interact with the Salesforce Objects through programming.

Ex:
Account, Contact, Opportunity, Lead, Case, Solution, Order,
Contract, Quote, ....etc, Position__C, Candidate__C, Loan__c, Student__C,
Hiring_MAnager__C,...etc.

Variables:
==========
Variable is nothing but a name to be get allocated for the memory location to
locate the value.

Variables are used to store the values temporarily inside the application during
the execution.
We can define one or more variables inside the application.

Syntax:
[Access Specifier] <DataType> <variableName> [= <Value>];

Ex:
integer customerCode;
string customerName;
string customerAddress;
Decimal balanceAmount;
Date birthDate;
Boolean isActive;

Note:
We can define the multiple variables in a single line as below.

Ex:
integer customerCode, age;
string customerName, address, designation;
Decimal balanceAmount, loanAmount;
Date birthDate, joiningDate, reievingDate;

Note:
Upon defining the variables, if the user didn't assigned any value, then Apex
will store the value as "Null" inside the variable.

Assigning the Values:


---------------------
Once the variable has been defined with a specific name, then we can store
the value inside the variable as below.

Syntax:
<variableName> = <Value>;

Ex:
customerCode = 100001;
age = 34;
customerName = 'Pawan Kumar';
Address = '#412, Satya Sai Apartments, Hyderabad';
balanceAmount = 12500.50;

Note:
We can define the variable and initialize the value for the variable in a
single line as below.

Ex:
integer productCode = 4000012;
string productName = 'Laptop Device';
decimal unitPrice = 35000;
Boolean isInStock = true;

Operators:
==========
Operator is nothing but a symbol, which is used to perform the operations on
the operands.

Apex provides the below category of operators.

1. Arithmetic Operators / Mathematical Operators:


These are used to perform the mathematical operations on the
values.

+
-
*
/
Math.Mod()

Ex:
5/2 = 2 (Quotient)
Math.Mod(5,2) = 1 (Reminder)

2. Relational / Comparison Operators:


These are used to compare the relation between the two values.

< <= > >= == != Equals()

3. Logical Operators:
These re used to prepare the Compound conditions by grouping the
multiple conditions together.

AND --> &&


OR --> ||
NOT --> !

4. Increment / Decrement Operators:

++ --> Increment --> Increment the Value by 1.

-- --> Decrement --> Decrement the value by 1.

Ex:
integer customerCode = 1001;
customerCode++; --> o/p: 1002

customerCode--; --> o/p: 1001

5. Assignment Operators

+=
-=
*=
/=
=

Ex:
integer balanceAmount = 25000;

balanceAmount += 4000; (balanceAmount =


balanceAmount + 4000)
|
---> O/p: 29000

balanceAmount -= 2000; --> O/p: 27000.

balanceAmount *= 2; (27000 * 2 = 54000)

balanceAmount /= 2; (54000 / 2 = 27000)


Output / Printing Statements:
=============================

C --> Printf("Message");
C++ --> Cout<<"Message";
Java --> System.Out.Println("Message");
C#.Net --> Console.WriteLine("Message");

Apex --> System.debug('Message to Print in Debug Log File.');

Syntax:
System.debug('Message to Print in Debug Log File.');

Ex:
System.debug('Welcome to Apex Programming.');
system.debug('This is my First Apex Program.');

Ways to Write the Apex Code:


============================
Salesforce provides the below 4 ways to write the apex code.

1. By using Standard Navigation.

2. By using Developer Console.

3. By using URL format.

4. By using "Execute Anonymous Window".


By using this Editor, we can Write, Compile, Execute and view the
result of the code.

Navigation:
Click on your name and expand it.
1. Click on "Developer Console" link.
2. Goto the "Debug" menu and expand it.
3. Click on "Execute Anonymous Window" link.
(OR)
From Developer Console, use the ShortCut "CTRL+E".
4. Write the Code inside the Editor.
5. Click on "Execute / Execute Highlighted" button.
6. View the Result inside the Debug Log File.

Ways to Execute the Apex Code:


==============================
Salesforce provides the below 9 ways to execute the apex code.

1. By using Execute Anonymous Window.


2. By using Triggers
3. By using Visualforce Page
4. By using Batch Programming
5. By using Schedule Programming
6. By using Process Builder
7. By using Email Services
8. By using WebServices / API's
9. By using "Visual Studio Code Editor (VS Code)".

UseCase:
========
Write an apex program, to print the Welcome message on the Debug Log file.

System.debug('Welcome to Apex Programming.');

Step 1:
Goto the Execute Anonymous Window.
Step 2:
Write the required code inside the Editor.
Step 3:
Select the CheckBox "Open Log".
Step 4:
Click on "Execute / Execute Highlighted".
Step 5:
Goto the "Developer Console" and Select the
CheckBox "Debug Only".
Step 6: View the Result.

UseCase:
========
Write an apex program, to define Two variables and print the values on the
Log File.

integer customerCode;
string customerName;

System.debug(customerCode);
System.debug(customerName);

system.debug('--------------------------------------------');

System.debug('Customer Code is...: '+ customerCode);


system.debug('Customer Name is...: '+ customerName);

100 + 600 = 700

Welcome + 3400 = Welcome3400

100 + Hello = 100Hello

Hello + Welcome = HelloWelcome

UseCase:
========
Write an apex program, to define the Two Integer variables and assign the
values and perform all the mathematical operations.

integer firstNumber, secondNumber, result;

firstNumber = 1000;
secondNumber = 50;

result = firstNumber + secondNumber;


system.debug('Addition Operation Result is...: '+ result);

result = firstNumber - secondNumber;


system.debug('Subtraction Result is.....: '+ result);

result = firstNumber * secondNumber;


system.debug('Multiplication Result is...: '+ result);

result = firstNumber / secondNumber;


system.debug('Division Result is....: '+ result);

result = Math.mod(firstNumber, secondNumber);


system.debug('Reminder Value is.....: '+ result);

UseCase:
========
Write an apex program, to Calculate the Simple Interest.

integer principleAmount, tenure, rateOfInterest, interestAmount;

principleAmount = 5000;
tenure = 10;
rateOfInterest = 4;

interestAmount = (principleAmount * tenure * rateOfInterest) / 100;


system.debug('Interest Amount is....: '+ interestAmount);

UseCase:
========
Write an apex program, to print the Sum of first 100 Numbers.
Formula:
1 + 2 +3 +4 +5 +........+ 100 = n (n+1)
-------
2
integer maxNumber, totalSum;

maxNumber = 50;

totalSum = (maxNumber * (maxNumber + 1))/2;

system.debug('Sum of first '+ maxNumber + ' Numbers is...: '+ totalSum);

Assignments:
============
1. Write an apex program, to calculate the BillAmount based on the Quantity
and UnitPrice.

2. Write an apex program, to Convert the Temperature from Centigrade to


Foreignheit.

3. Write an apex program, to Convert the Temperature from Foreignheit to


Centigrade.

Conditional Statements:
=======================

Apex provides the below 3 Conditional Statements.

1. IF Condition
2. Switch Statement (Summer'18 Release)
3. Ternary Operator

IF Condition:
=============
By using the IF Condition, we can add one or more user defined conditions to
be get verified before executing the statements.

If the conditions are satisfied, then it will execute the Statements. Else it
will skip the execution of the statements.
By using IF conditions, we can change the control flow of the program
execution.

IF conditions provides the below 4 formats.

1. Simple IF Conditions
2. If Else Condition.
3. Else If Condition
4. Nested IF Condition

Simple IF Condition:
--------------------
Syntax:
If(<Conditions>)
{
// Write the Statements..
}

Note:
Each Condition should follow the below syntax..
Syntax:
<VariableName> <operator> <Value>

Ex:
Rating == 'Hot'
SecondNumber > 0
Industry == 'Finance'
Phone != Null
isActive == true

Industry == 'Banking' && AnnualRevenue > 2000000


Location__c == 'Bangalore' && Minimum_pay__C < 1500000

UseCase:
--------
Write an apex program, to perform the Mathematical operations on the
Two Numerical values.

integer firstNumber, secondNumber, result;

firstNumber = 1000;
secondNumber = 0;

result = firstNumber + secondNumber;


system.debug('Addition Operation Result is...: '+ result);

result = firstNumber - secondNumber;


system.debug('Subtraction Result is.....: '+ result);

result = firstNumber * secondNumber;


system.debug('Multiplication Result is...: '+ result);

if(secondNumber > 0)
{
result = firstNumber / secondNumber;
system.debug('Division Result is....: '+ result);

result = Math.mod(firstNumber, secondNumber);


system.debug('Reminder Value is.....: '+ result);
}

If Else Condition:
------------------
Syntax:
If(<Conditions>)
{
// Write the Statements.. (True Block Statements)
}
else
{
// Write the Statements.. (False Block Statements)
}

UseCase:
--------
Write an apex program, to perform the Mathematical operations on the Two Numerical
values.

integer firstNumber, secondNumber, result;

firstNumber = 1000;
secondNumber = 0;

result = firstNumber + secondNumber;


system.debug('Addition Operation Result is...: '+ result);

result = firstNumber - secondNumber;


system.debug('Subtraction Result is.....: '+ result);

result = firstNumber * secondNumber;


system.debug('Multiplication Result is...: '+ result);

if(secondNumber > 0)
{
result = firstNumber / secondNumber;
system.debug('Division Result is....: '+ result);

result = Math.mod(firstNumber, secondNumber);


system.debug('Reminder Value is.....: '+ result);
}
else
{
System.debug('We cannot perform Division and Modulus Operations. As the
Second Number is Zero.');
}

/*
Write an apex program, to find out the Biggest Number from the Given Two
Numbers.
*/

integer firstNumber, secondNumber;

firstNumber = 4500;
secondNumber = 6700;

if(firstNumber > secondNumber)


{
system.debug('First Number is the Biggest One.');
}
else
{
system.debug('Second Number is the Biggest One.');
}

UseCase:
--------
Write an apex program, to find out the Student Result as below.
1. We have the 5 Subjects (English, Maths, Physics, Chemistry, Hindi)
2. PASS: If the student got more than 40 Marks in each subject.
3. FAIL: IF the student got less than 40 marks in any of the subject.

if(maths >= 40 && physics >= 40 && hindi >=40 && english >= 40 && chemistry >= 40)
{
System.Debug(PASS);
}
else
system.debug(FAIL)

UseCase:
--------
Write an apex program, to find out the Bill Amount of the Customer based on
the Quantity and Unit Price. And offer the discount as below.
1. Amount > 10,000, then Offer 20% discount.
2. Else No Discount provided to Customer.

Else IF Condition:
==================
Syntax:
IF(<Conditions>)
{
// Write the Statements..
}
else if(<Conditions>)
{
// Write the Statements..
}
else if(<Conditions>)
{
// Write the Statements..
}
...
...
else
{
// Default Block Statements..
}

This feature is used to prepare the multiple branches of conditions from which only
one branch statements will be executed at a time.

If any of the branch conditions are matching / satisfied, then it will execute the
associated block of statements.

If all the branch conditions are failed, then it will execute the "Else Block
Statements".
UseCase:
--------
Write an apex program, to find out the Biggest Number from the given two
numbers.

integer firstNumber, secondNumber;

firstNumber = 114500;
secondNumber = 2314500;

if(firstNumber == secondNumber)
{
system.debug('Both the Numbers are Identical.');
}
else if(firstNumber > secondNumber)
{
system.debug('First Number is the Biggest One.');
}
else
{
system.debug('Second Number is the Biggest One.');
}

/*
Write an apex program, to print the Season Name based on the Month Number as
below.

Month Number Season Name


------------------------------------------
1 - 4 Winter Season
5 - 8 Summer Season
9 - 12 Spring
Season
<1 OR >12 Invalid Month
Number
*/

integer monthNumber = 17;

if(monthNumber >= 1 && monthNumber <=4)


{
system.debug('Winter Season.');
}
else if(monthNumber >= 5 && monthNumber <= 8)
{
system.debug('Summer Season.');
}
else if(monthNumber >= 9 && monthNumber <= 12)
{
system.debug('Spring Season.');
}
else
{
system.debug('Invalid Month Number. Please Enter month Number between 1 -
12.');
}

/*
Write an apex program, to print the Month Name based on the Month Number as
below.

Month Number Month Name


-----------------------------------
1 January
2 February
3 March
...
12 December
<1 OR >12 Invalid Month Number.
*/

Nested IF Condition:
====================
By using this feature, we can include / insert an if condition into an another
condition to achieve the complex functionalities.

Syntax:
If(<Conditions>)
{
// Write the Statements..
}
else
{
// Write the Statements..

if(<Conditions>)
{
// Write the Statements..

if(<Conditions>)
{
// Write the Statement...
}
}
else
{
// Write the Statements..
}
}

/*
Write an apex program, to find out the Student Result and Grade as below.

1. We have 5 Subjects for the Student (Ex: English, Hindi, Maths,


Physics, Chemistry)
2. Calculate the Total Marks of the Student.
3. Find out the Student Result.
3.1. PASS : If the student got more than 40 marks in each
subject.
3.1.1. Print the Student Result and Total Marks.
3.1.2. Calculate the Average Marks of the Student.
3.1.3. Findout the Student Grade as below.
Average Marks
Grade
-----------------------------
--
>= 60
GRADE A
>=50 && <60
GRADE B
>=40 && <50
GRADE C

3.2. FAIL : If the student got less than 40 marks in any of


the subject.
3.2.1. Print the Student Result and Total Marks.
*/

integer english, hindi, maths, physics, chemistry, total, average;

english = 72;
hindi = 81;
maths = 19;
physics = 79;
chemistry = 86;

total = english + maths + physics + chemistry + hindi;

if(english >= 40 && maths >= 40 && hindi >= 40 && physics >= 40 && chemistry
>= 40)
{
system.debug('Congratulations..!! You got PASSED.');
system.debug('Total Marks are....: '+ total);

average = total / 5;
system.debug('Average Marks are....: '+ average);

if(average >= 60)


system.debug('GRADE A.');
else if(average >= 50 && average < 60)
system.debug('GRADE B.');
else if(average >= 40 && average < 50)
system.debug('GRADE C.');
}
else
{
system.debug('You got FAILED. Better luck Next Time.');
system.debug('Total Marks are....: '+ total);
}

Switch Statement:
=================
Switch Statement is used to compare the variable / expression value with the
various branches.

If any of the Branch Value is matching with the expression, then it will execute
the associated block of statements.

If any of the Branch value is not matching with the expression, then it will
execute the default block statements.

Syntax 1:
---------
Switch ON <Expression / Value>
{
When <Value1>
{
// Write the Statements..
}
When <Value2>
{
// Write the Statements..
}
When <Value3>
{
// Write the Statements..
}
...
...
When Null
{
// Write the Statements..
}
When Else
{
// Default Block Statements..
}
}

UseCase:
--------
Write an apex program, to print the Day Name based on the Day Number as
below.

Day Number Day Name


-----------------------------
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
...
7 Sunday
<1 Or >7 Invalid Day Number.

integer dayNumber = 15;

Switch ON dayNumber
{
When 1
{
system.debug('Monday.');
}
When 2
{
system.debug('Tuesday');
}
When 3
{
system.debug('Wednesday');
}
When 4
{
system.debug('Thursday');
}
When 5
{
system.debug('Friday');
}
When 6
{
system.debug('Saturday');
}
When 7
{
system.debug('Sunday');
}
When Else
{
system.debug('Invalid Day Number.');
}
}

Syntax 2:
---------
Switch ON <Expression / VariableName>
{
When <Value1>,<Value2>,<Value3>,...,<ValueN>
{
// Write the Statements..
}
When <Value11>,<Value21>,<Value31>,...,<ValueN1>
{
// Write the Statements..
}
...
...
When Else
{
// Write the Default Block Code..
}
}

In this feature, it will compare the Variable / expression value with a collection
of elements.

if any of the branch element is matching with the expression, then it will execute
the block of statements.

If any of the branch value is not matching with the expression, then it will
execute the Default Block Statements.

/*
Write an apex program, to print the Season Name based on the Month Number as
below.

Month Number Season Name


------------------------------------------
1 - 4 Winter Season
5 - 8 Summer Season
9 - 12 Spring
Season
<1 OR >12 Invalid Month
Number
*/

Integer monthNumber = 22;

Switch ON monthNumber
{
When 1, 2, 3, 4
{
system.debug('Winter Season.');
}
When 5,6,7,8
{
system.debug('Summer Season.');
}
When 9,10,11,12
{
system.debug('Spring Season.');
}
When else
{
system.debug('Invalid Month Number. Please Enter the Number
between 1 - 12.');
}
}

Iterative Statements:
=====================
These are used to execute a block of statements iteratively / continuously till the
required number of times based on the application requirement.

By using Iterative Statements, we can reduce the number of lines of code. So that
we can avoid the Duplicate code and we can improve the application performance.

Apex Provides the below 4 Iterative Statements.

1. While
2. Do-While
3. For
4. Enhanced FOR Loop.

While Statement:
================
Syntax:
While(<Conditions>)
{
// Write the Statements..
}

It is a Pre-Checking iterative statement, which will verify the condition first.


Once the condition get satisfied, then it will execute the block of statements.

It will execute the statements iteratively till the specified conditions get
satisfied. Once the Condition get failed, then it will comes out of the block
automatically.

/*
Write an apex program, to Print the Welcome Message 10 Times on the Debug Log
File.
*/
integer counter = 1;

While(counter <= 10)


{
System.debug('Welcome to Apex Programming');

counter++;
}

/*
Write an apex program, to print the Numbers between 1 - 100.
*/

integer counter = 1;

While(counter <= 100)


{
system.debug('Number is...: '+ counter);

counter++;
}

/*
Write an apex program, to Print the Even Numbers between 1 - 50
*/
integer counter = 2;

While(counter <= 50)


{
system.debug('Even Number is....: '+ counter);

counter += 2;
}

Assignments:
============
1. Write an apex program, to print the Odd Numbers between 1 - 100.

2. Write an apex Program, to print the numbers between 1 - 50 in reverse


order.

3. Write an apex program, to print the Even Numbers between 1 - 100 in


reverse order.

4. Write an apex program, to Check whether the given number is an Even Number
or not.

/*
Write an apex program, to print the Mathematical Table for the given number
as below.
(
Ex:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
...
...
5 * 10 = 50
)
*/

integer maxNumber = 1485;


integer counter = 1;

While(counter <= 20)


{
system.debug(maxNumber + ' * '+ counter + ' = '+ (maxNumber *
counter));

counter++;
}

Do-While Statement:
===================
Syntax:
Do
{
// Statements..
...
...
}While(<Conditions>);

It is a Post-Checking iterative statement, which will execute the statements


at least once, and then it will verify the conditions.

It will continuously execute the statements till the condition get satisfied.
Once the Condition get failed, then it will comes out of the block.

/*
Write an apex program, to print the Odd Numbers between 1 - 50 in reverse
order.
*/

integer counter = 49;

Do
{
system.debug('Odd Number is....: '+ counter);

counter -= 2;
}While(counter >= 1);

Assignments:
------------
1. Write an apex program, to check whether the given Number is a Prime Number
or not.
(Ex: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...etc.)

2. Write an apex program, to Print the Numbers from 50 - 1 using Do-While


Statement.

FOR Loop:
=========
Syntax:
for(<Initialization Part>; <Conditions Part>; <Increment / Decrement Part>)
{
// Write the Statements..
...
...
}

It is a Pre-Checking Iterative Statement, which provides an optimized way of using


iterative statements inside the programming.

/*
Write an apex program, to Print the Mathematical Table for the given number.
*/

for(integer counter = 1, maxNumber = 345; counter <= 10; counter++)


{
system.debug(maxNumber + ' * '+ counter + ' = '+ (maxNumber *
counter));
}

Arrays:
=======
Arrays are used to hold a collection of Homogeneous Elements. i.e. Arrays can store
a collection of similar DataType elements.

We can't store the Heterogeneous(Different DataType) elements inside the Array.

While Creating the Array, we have to specify the "Size", which describes the number
of elements can be hold inside the array.

We can't Increase / Decrease the Array Size at runtime. So, arrays causes the
memory wastage.

Each Element inside the array will be identified by using an "Index Position"
starting from "Zero".

Each element inside the array will be identified by using "Array Name along with
the Index Position".

Syntax:
<Datatype>[] <arrayName> = new <DataType>[Size];

Ex:
Integer[] customerCodes = new Integer[10];
|
--> Holds 10 Integer elements.

String[] countryNames = new String[200];


|
--> Holds 200 String elements.

ID[] recordIds = new Id[5];


|
--> Holds 5 Record Id's.

Account[] accRecords = new Account[25];


|
--> Holds 25 Account Records.

Case[] caseRecords = new Case[50];


|
--> Holds 50 Case Records.
Position__C[] positionRecords = new Position__C[70];
|
--> Holds 70 Position Records.

Loan__c[] loanRecords = new Loan__c[100];


|
--> Holds 100 Loan Object Records.

Assigning the Elements:


-----------------------
We can assign the elements to array as below.

Syntax:
<arrayName>[IndexPosition] = <Value>;

Ex:
Integer[] customerCodes = new Integer[10];

customerCodes[0] = 1190045;
customerCodes[1] = 6677;
customerCodes[2] = 9900;

Retrieving the Array Elements:


------------------------------
We can retrieve the array elements as below.

Syntax:
<ArrayName>[IndexPosition];

Ex:
System.debug('Customer Code is...: '+ customerCodes[0]);
System.debug('Customer Code is...: '+ customerCodes[1]);

UseCase:
--------
Define an Array and Print the Array Elements on the Debug Log File.

// Defining an Array..
Integer[] customerCodes = new Integer[5];

// Print the Array Elements..


system.debug('Customer Codes are.....: '+ customerCodes);

system.debug('------------------------------------------');

// Assigning the Values..


customerCodes[0] = 5600;
customerCodes[1] = 4567;
customerCodes[2] = 9900;
customerCodes[3] = 5644;
customerCodes[4] = 7788;

system.debug('Customer Codes are...: '+ customerCodes);

system.debug('----------------------------------------');

// Print the Elements in separate rows..


system.debug('Customer Code...: '+ customerCodes[0]);
system.debug('Customer Code...: '+ customerCodes[1]);
system.debug('Customer Code...: '+ customerCodes[2]);
system.debug('Customer Code...: '+ customerCodes[3]);
system.debug('Customer Code...: '+ customerCodes[4]);

system.debug('------------- FOR LOOP --------------------');


// Print the Elements using FOR Loop..
for(integer counter =0; counter <= 4; counter++)
{
system.debug('Customer Code is...: '+ customerCodes[counter]);
}

system.debug('--------------- ENHANCED FOR LOOP -------------');


// Print the Elements by using Enhanced FOR Loop..
for(integer code : customerCodes )
{
system.debug('Customer Code Value.....: '+ code);
}

/*
Define an Array to manage a collection of string elements, and assign the
elements
upon defining the array.
*/
// String Array..
string[] countryCodes = new string[]
{'India','USA','UK','Japan','China','Germany','Middle East'};

for(string code : countryCodes )


{
system.debug('Country Name is...: '+ code);
}

system.debug('----------------------------------');
// Integer Array..
Integer[] employeeCodes = new Integer[]{1001, 1002, 1003, 1004, 5600};

for(integer code : employeeCodes)


{
system.debug('Employee Code is....: '+ code);
}

Assignments:
============
1. Write an apex program, to Manage a collection of Employee Names by using
Arrays.

2. Write an apex program, to Manage a collection of Department Names by using


Arrays.

3. Write an apex program, to manage a collection of AccountNumbers by using


Arrays. (Numerical Elements)

4. Write an apex program, to manage a collection of Record ID's by using


Arrays.
Java ------> JDBC Drivers -----> Oracle
MS.Net ----> ADO.Net ------> Oracle

Apex ------> Salesforce Database.

You might also like