Sie sind auf Seite 1von 30

APEX: It is World’s First Cloud based Strongly Typed Object Oriented Programming Language and it is the Proprietary Language of

Salesforce Company.

 It is used for to develop or implement complex business functionality.


 We can create Web services integrating with other systems by using APEX.
 We can create Email Services using Apex
 We can perform Complex and Custom validation over multiple objects simultaneously.
 Create complex business processes that are not supported by existing workflow functionality.

Feature of Apex:

1. STRONGLY TYPED LANGUAGE: It is Strongly Typed Language, so every variable in Apex will be declared with the specific data
type. All apex variables are initialized to null initially. It is always recommended for a developer to make sure that proper
values are assigned to the variables.
2. Similar to Java Syntax: Apex syntax is just like Java Syntax such as variable declaration, Loop Sytnax, Conditional Statement
syntax ,Class syntax etc.,
3. Integrated with Data: Apex can integrate with all types of DML statements such as INSERT, UPDATE, DELETE. We can easily
embed with SOSL and SOQL Statements with Apex coding.
4. It Supports Multitenant Architecture.
5. Apex automatically upgraded whenever the new version releases, we no need to upgrade Manually.
6. It is a case insensitive language.
7. It upgrades automatically, it means we no need to upgrade our development kit or compiler or interpreter.
8. It is very easy to test, it provides built in support or functionality to write and execute the test cases.
9. It runs on Multitenant Environment.

Working Style of Apex:

When to Use APEX:

1. When we want to do some automation that cannot be implemented using workflows and process builder in that case we have
to write the code in Apex Trigger.
2. When we need to write complex validation rules. For Ex we want to validate that the account we are creating do not have
phone number or email id similar to any of the other account that you have available. So, those kind of validations are not
possible through point and click (configuration) for that we need to write a code in Apex.
3. If we want to interact with external application we need to use web services (integration) and creating email services for that
we need to use Apex.
4. Whenever we want to do certain transactions and we need to control those transactions using some savepoints and rollbacks
we can use Apex.

Limitations of Apex:

1. Apex is not available in Professional Edition, Governor Limits, Code is not maintnable as compared to the point and click tools
and declarative approaches.
2. We cannot show anything on UI(user Inteface) using Apex, except Error Messages.
3. Using Apex we cannot change any salesforce functionality. We can only add new functionality and stop the execution of the
existing functionality to do particular action.
4. Apex cannot create any temporary files. So there is no file handling concept in Apex.
5. We cannot create multiple threads in Apex.
Data Types in APEX:

In Apex Data types are broadly divided into 2 types.

1. Simple Data types


2. Complex Data type.

Simple Data types:

1.Integer : This data type allows us to enter Integer values such as either positive or negative numbers. The range of this
datatype is -2117483648 to +2117483647.
Ex: Integer roll_number=1001;

2. Long: This data type allows us to enter Integer values such as either positive or negative numbers. The range of this data
type is 2^63 to 2^63-1. It allows us to enter the value like mobile numbers, Account Number etc.,

Ex: Long Acno=5010028266899L;

3. Decimal: This data type allows us to enter decimal values such as employee salary, student fees which are particularly currency
field values.
Ex: Decimal salary=9875.97;
4. Double: This data type allows us to enter decimal values. Ex: Double total_balance=98535252.9525;
5. Boolean: This data type allows us to enter true or false values. Ex: Boolean status=true;
6. String: This data type allows us to enter String values such as names etc., Ex: String iname=’oscar it’;
7. Date: This data type allows us to enter date values such as joining date etc.,
Ex: date variable name= date.newInstance(yyyy,mm,dd); Date hiredate =date.newInstance(2019,08,15);
8. Time: This data type allows us to enter time values such as login time etc.,
time variable name= time.newInstance(hh,mi,ss,ms); ex: Time login_time = time.newInstance(10,15,40,49);
9. DateTime: This datatype allows us to enter Datetime both. DateTime Variable name =
datetime.newInstance(yyyy,mm,dd,hh,mi,ss); DateTime dt= datetime.newInstance(2019,10,06,09,08,45);
10. Void: This data type does not return any value, Especially we use this operator while using functions.

Void methodname(sequence of arguments);

Complex Data types:

1. ID: It allows us to enter Alphanumeric values. The maximum length of this data type is 15 digits.
These ID’s are not entered by user, it is automatically generated by SF. It is always unique value.
Ex: Car number, Student Id etc.,
2. Binary Large Object(BLOB): It allows us to enter any kind of Image, MMS, Text files, Audio, Video files etc.,
3. Sobject: It is a storage space, it stores the data in the form of rows and cols. Matrix format.

Operators In Apex:

Operator: Operator is a special symbol which performs some operations on operands.


1. Arithmetic Operators: a=10 b=5
+ -- addition -- a+b-- 10+5 =15
- -- subtraction -- a-b -- 10-5 =5
/ -- div -- a/b -- 10/5 = 2
* -- multiplication - a*b - 10*5 =50

2. Relational operators: >, <, >= , <= , == , !=


3. logical operator: && -- and , || -- or , ! -- not
4. Incremental operator: ++
a=a+1=> a++ (post Increment) : Variable value will increment after executing the statement.
++a (pre increment) : Variable value will increment before executing the statement.
Ex: Integer a=10 b,c;
b=2*(a++);
c=2*(++a);
system.debug(b);
system.debug(c);
5.Decremental Operator: --
a=a-1=> a-- (post decrement) : Variable value will decrement after executing the statement.
--a (pre decrement) : Variable value will decrement before executing the statement.
Ex: Integer a=10 b,c;
b=2*(a--);
c=2*(--a);
system.debug(b);
system.debug(c);
6.Arithmetic Assignment: +=, -=, *=, /= (more than 1)
A=a+10 => a+=10
B=b-5 => b-=5
C=c*4 => c*=4
D=d/3 => d/=3
7.Assignment Operator: =
8. Bitwise Operators: >> Right Shift, << Left Shift
9. Conditional Operators: ? :
10. Special Operators: , , . , [,],{,},(,),this
Rules for creating variables/identifier:

1. Variable name must starts with an alphabet and it contains minimum 1 character and maximum 256 characters.
2. It does not allowed any kind of special characters except _ and 0 to 9 numbers.
3. Variables names should not use any keywords.
4. It is not case sensitive a and A both are same.
Ex: student valid
Student123 valid
123student invalid
_123student invalid
Student#123 invalid
Syntax to declare a variable:
Datatype identifier/variable; or Datatype Identifier/Variable = Value;
Ex: integer sno; or Integer sno=1001

Input & Output Statement:

In Apex, there is no input and output statements,


If we want to input the values at runtime then we need to enter through Visual Force pages it is just like HTML page.
And output we can see in LOG file.
Administrator will work on LOG file it is used to debugging file or monitoring purpose.
But how to write the contents into a LOG file, by using the following statement i.e System.debug()
Syntax 1:
System.debug(‘Message’);
Ex:
System.debug(‘Oscar IT’);  the same message as it is printed in the LOG file
Syntax 2:
System.debug(variable name);
Ex:
System.debug(a); the value of ‘a’ will be printed in the LOG file.
Syntax 3:
System.debug(‘Message’ + variable name);
Ex:
Systeme.debug(‘the value of a is ‘ + a) the value of a is 10 will printed in the Log file, if a value is 10.
Comments in Apex:
Comments are used to increase the readability of the program comprehensively. There are 2 types of comments in Apex.
One is Single line comment and the other is Multiline Comment.
Single Line Comment: //
Multi Line Comment : /*----------------------------------------------------------*/

Programs:

1st Program: Print Oscar I.T Solutions


System.debug(‘Oscar I.T Solutions’);

2nd program: Add two numbers


Integer a,b;
A=10;
B=20;
System.debug(‘the sum is ‘ + (a+b));

3rd program: Arithmetic Operations


Integer a,b;
A=10;
B=20;
System.debug(‘the sum is ‘ + (a+b));
System.debug(‘the subraction is ‘ + (a-b));
System.debug(‘the product is ‘ + (a*b));
System.debug(‘the division is ‘ + (a/b));

4th Program: Swapping of Two numbers


Integer a,b;
A=10;
B=20;
B=a-b;
A=a-b;
B=a+b;
System.debug(‘the value of a is’ + a);
System.debug(‘the value of b is ‘ + b);

5th program: Convert Feet into Inches


Integer Feet;
Feet=10;
System.debug(‘the number of inches is ‘ +(feet*12));

6th program Incremental Operator


Integer a,b,c;
A=2;
B=2*(a++);
C=2*(++a);
System.debug(‘the value of b is ‘+ b);
System.debug(‘the value of c is ‘ + c);

7th program: Decrement operator


Integer a,b,c;
A=2;
B=2*(a--);
C=2*(--a);
System.debug(‘the value of b is ‘+ b);
System.debug(‘the value of c is ‘ + c);

Control Statements: These statements are used to control the flow of execution of the program.
By default, execution begins from top of the program and ends with bottom of the program and every statement gets executed only once.
Sometimes this flow might not be accepted, depending up on some values, depending upon certain conditions,
Some statements should get executed, some statements should not executed, some statements should skipped, and some statements
should executed repeatedly.
For this, we have 3 types of Control Statements.
1. Simple condition control Statements: Statements are executed once based on some condition or Skips the statements. Ex: if - else
2. Iterative Control Statements: Statements are executed repeatedly based on some condition.
Ex: for loop, for each, while and do – while loop
3. Jump Statements: moves the control from one block of statements to another block of statements.
Goto , break, function call, return .

IF-Condition:

1. simple If ,2. if – else ,3. if- else if (series of If else ), 4. nested if, 5. series of if(collection of simple if, no else).

Syntax of Simple If:

If(condition)
{
Statement 1;

Statement n;
}

Syntax of If-Else:

If(condition)
{
Statement 1;

Statement n;
}
Else
{
Statement 1;

Statement n;
}

Sytnax of If-Else-If

If(condition)
{

Statement 1;

Statement n;

Else

if

Statement 1;

Statement n;

Syntax of Series of Ifs:

if(condition)
{
Statement 1;
Statement n;
}
If(condition)
{
Statement 1;
Statement n;
}
Syntax of Nested If:

If(condition)
If(condition)
{
Statement 1;
Statement n;
}
Else
{
Statement 1;
Statement n;
}
Else
If(condition)
If(condition)
{
Statement 1;
Statement n;
}
Else
{
Statement 1;
Statement n;
}
}

Programs:

1st Program: Simple If


Integer Age;
Age=18;
If(age>=18)
System.debug(‘Eligible for Voting’);

2nd program: If – else


Integer age;
Age=18;
If(age>=18)
System.debug(‘Eligible for Voting’);
Else
System.debug(‘Not eligible for Voting’);

3rd program: two numbers Find the biggest number


Integer a,b;
A=10;
B=20;
If(a>b)
System.debug(‘a is big’);
Else
If(b>a)
System.debug(‘b is big’);
Else
System.debug(‘both are equal’);

4th program: 3 numbers Find the biggest number


Integer a,b,c;
A=10;
B=20;
C=30;
If(a>b &&a>c)
System.debug(‘a is big’);
Else
If(b>c)
System.debug(‘b is big’);
Else
If(a==b && a==c)
Sytem.debug(‘ all are equal’);
Else
System.debug(‘c is big’);

5th program : Power Bill calculation


Integer cno,srno,erno,uc,tb;
String cname,st;
Cno=101;
Cname=’Raj’;
Srno=1000;
Erno=1500;
St=’industry’;
Uc=erno-srno;
If(st==’industry’)
Tb=uc*5;
Else
If(st==’commercial’)
Tb=uc*4;
Else
If(St=’residence’)
Tb=uc*3;
System.debug(‘the total bill is ‘+ tb);

6th program: Power bill calculation using Nested If


Integer cno,srno,erno,uc,tb;
String cname,st;
Cno=101;
Cname=’Raj’;
Srno=1000;
Erno=1500;
St=’residence’;
Uc=erno-srno;
If(st==’industry’)
If(uc<=100)
Tb=uc*5;
Else
Tb=uc*6;
Else
If(st==’commercial’)
If(uc<=100)
Tb=uc*4;
Else
Tb=uc*5;
Else
If(St==’residence’)
If(uc<=100)
Tb=uc*3;
Else
Tb=uc*4;
System.debug(‘the total bill is ‘+ tb);

7th program: Series of Ifs:


Integer a,b,c,max;
A=10;
B=20;
C=30;
Max=a;
If(b>max)
Max=b;
If(c>max)
Max=c;
System.debug(‘the biggest number is ‘ + max);

2.Iterative Statements (Loops): Whenever we need to execute a single statement or set of statements repeatedly, then we need to use
Loops. Loops are divide into 2 types.

1. Range Based Loops 2. Conditional Based Loops:

Range Based Loops: A Range based loop is a loop statement which executes the statements as long as the initial value reaches the final
value. Once control Crossed the final value then control automatically comes of the loop.

Ex: For Loop , For Each Loop.

Syntax of For Loop:

For(initialization;condition;incrementation/decrementation)
{
Statement 1;
Statement n;
}
Ex:
Integer I;
For(i=1;i<=10;i++)
{
System.debug(i);
}
Note: For Each loop we will discuss in Collections Topic.

Conditional Based Loops: A condition based loop is a loop statement which executes the statements as long as the given condition is
satisfied. Once condition is false then control automatically comes of the loop.

Ex: While , Do – While

Syntax of While Loop:

While(condition)
{
Statement 1;
Statement n;
}

Ex:

Integer I=1;
While(i<=10)
{
System.debug(i);
I++;
}

Syntax of Do-While:
Do
{
Statement 1;
Statement n;
} while(condition);

Ex:
Integer i=1;
Do
{
System.debug(i);
I++;
}while(i<=10);

3.Jump Statements: In these statements Control will move from one block of the program to another block of program.
Ex: Return, Go to, Exit, continue etc.,

Functions:

Definition: A function is a self contained block which performs a specific task.


Advantage: Code Reusablity.
Property: It returns only one value.
Types of Functions : 1. Predefined Functions 2. Programmer Defined Functions.
Function has two parts.
1. Function Prototype (calling Point)
2. Function Definition (Called Point)
Function prototype again divided into 4 parts
1. Return type.
2. Function/method name.
3. List and Sequence of Arguments
4. ;
Function Definition again Divided into 2 parts
1. Function Header.
2. Function Body.
Function Header contains 3 parts.
1. Return type.
2. Function/method name.
3. List and Sequence of Arguments.
Function Body: It contains the actual Business Logic.

When we need to write functions:


We have 3 instance we need to write functions.
1. Whenever same task we need to perform repeatedly or again and again, write once use many times.
Ex: landline  redial
2. Split task (program) into sub tasks or sub program. This is called modularity.
3. It is used to overcome the limitations of Operators. Suppose every operator denoted by a symbol, but we have 1000s of
operations but we don’t have 1000s of operators. Suppose finding the sqrt, or finding the power of any value for these
operations there is no separate operators. But this we can achieve through functions.

Programs:
1st program: Addition of two number
Integer a,b,c;
A=10;
B=20;
C=add(a,b);
System.debug(‘the sum is ‘+ c);

Integer add(int x, int y)


{
Int z;
Z=x+y;
Return z;
}

2nd program : addition and subtracation


Integer a,b,c,d;
A=10;
B=20;
C=add(a,b);
D=sub(a,b);
System.debug(‘the sum is ‘+ c);
System.debug(‘the subtraction is ‘ + d);
System.debug(‘the sum is ‘+ c);
Integer add(int x, int y)
{
Int z;
Z=x+y;
Return z;
}
Integer sub(int x, int y)
{
Int z;
Z=x-y;
Return z;
}

3rd program : functions using If condition


Integer cano,cb,tamt,tb;
String cname,tc;
cano=101;
cname='Raj';
cb=10000;
tamt=5000;
tc='deposit';
if(tc=='withdraw')
tb=wd(cb,tamt);
else
tb=dep(cb,tamt);
System.debug('the sum is '+ tb);

//function definition
Integer wd(Integer x, Integer y) // function header
{
Integer z;
z=x-y;
return z;
} // function body
Integer dep(Integer x, Integer y)
{
Integer z;
z=x+y;
return z;
}

OBJECT ORIENTED PROGRAMMING:

Full Form: Object Oriented Programming

What is this?

It is a concept or It is Collection of Principles or it is one kind of Approach or it is a paradigm, These principles or concept was developed
by Mr. Grady Booch. So we can call him as Father of OOPs.

What are these principles:

1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance

Whichever programming language incorporate these 4 principles, then those languages can be called as Object Oriented Programming
Languages(OOPL)

Examples for OOPL: C++,Java,C#, APEX,ABAP…..

Languages

Programming languages are of 5 generations

1. Monolithic Language -- Basic


2. Structured Language --- Cobol
3. POPL-- C
4. OBL -- ADA
5. OOPL – C++,JAVA, APEX

What are the differences between POPL and OOPL:


POPL OOPL
1. It is Top to Down Approach 1. It is Bottom to Up Approach.
2. It is Less Secure 2. It is More Secure
3. It is divided into Functions 3. It is divided into Objects
4. Data can move from one function 4. Objects can move & communicate with each other
To another freely. through member functions.

Let Us Discuss about OOPs Principles:

1.Encapsulation:
Binding of Programming Elements(PE) i.e Data and Instruction in a single unit. (OR)
Binding of STATE(DATA/PROPERTY) AND BEHAVIOR(FUNCTIONALITY) as single unit is known as
ENCAPSULATION. (DATA+FUNCTIONALITY).
Ex: Our Hands are helps us to Eat and Write, so hear Hand is a data and eat and write are the functionalities.

We can implement Encapsulation by using 2 Keywords in Apex.


1. Class 2. Interface
Class:
It is a blue print or it is a drawing of an object means how object is look like and how object is represented that we can do by
having a class.
1) It is a blue print of real world existence. (or)
2) It is a collection of features and behaviors. (or)
3) It is a collection of data members and member methods. (or)
4) It is a user defined data type.
We identify something in this world by its features and behaviors. We can denote Features as Data and we can denote
Behaviors as Methods.

Syntax of Class:
Class <Class name>
{
Data Members; -- Features
Member Methods; -- Behaviors
}
Ex:
Class Student
{
Integer sno,tm;
String sname;
Decimal avg;
Total_Marks();
Avg_Marks();
}
.
Member Methods: It is of 4 types.
1. Create 2.Input 3. Process 4. Output.

Every member method gives some service to data members. If any member method does not give any service to data members, then
there is no point of writing the member method with in the class.

Interface: It contains Method Prototypes only.

Note: We will Discuss about Interface Later.

Object: It is a real world entity, means what we can see and what we can touch, feel is known as Object such as, Fan, Chair etc.,
Every object has some STATE and BEHAVIOUR ,State means Properties (data) and Behavior means Functionalities (methods).
For ex Take a Class called HUMAN From Human class we can derive two objects i.e MEN and WOMEN.
MEN properties like Name, Height, Weight, Color etc., Behavior like eat(),walk(),Write(), Read() etc.,
So same kind of properties and behavior for Woman also but there are some different functionalities between MEN and WOMEN i.e like
MEN cannot give the birth to a child but where are WOMEN can.
Another example:
Every MEN and WOMEN have 2 legs, 2 hands, 2 eyes,2 ears,1 nose, 1 mouth this is common parts for both MEN and WOMEN some of the
parts of the will differ from MEN and WOMEN. This is property differences.
Definition of an Object:
1. It is an instance of a Class
2. It is a real world existence of class
3. It is a variable of type class
How to create an object:
Dataype name;
Classname objectname = new classname();
1 2 3 4
Here

1. classname – represents-- data type


2. objectname – represents – variablename
3. new= dynamic memory allocation . object always allocated memory through dynamic memory allocation.
What is memory allocation: Allocation means reservation, reserve what? i.e main memory (RAM)
We can allocate the memory in 2 ways
1. Static Memory Allocation: memory will be allocated at the compilation time or translation time.
Suppose we written this statement
Datatype variablename;
Integer a; --- > static memory allocation
Suppose we wrote a program of 75 lines
5 10 15 20 25 30 35 40 45 50 55 60 65 70
All these statements have the following statement
Data Type variable name;  this statement we written in above mentioned lines
First this program need to translate into machine language
And starts the execution—just before start the execution it allocates memory and then starts the execution. This is called
Static memory allocation.
2. Dynamic Memory Allocation:
Datatype variablename = new datatype();
When we create any object then it always it is dynamic
4.classname()—constructor name
note: class name and constructor name must be same.
what is constructor:
1.It is special member method, because classname and constructor name must same.
2. It is called only once in the life time of an object, when the object is created.
3. It is always preceded by new operator.
4. Its job to load the values into data members when object gets created( initialize the values to data members).
5. It does not have any return type not even void
Who will execute the Apex code?
ARE—Apex Runtime Engine will take the responsibility to execute the Apex code
Whatever code we written, that code will talk to ARE and ARE will execute the Code.
ARE has to start the execution, in Apex this main requires which we need to write it as ‘testMethod’
We need to write like this
Public static testMethod void main() – this is the starting point of execution of Apex program.
2) ABSTRACTION:

It means only showing the required things to the outside world so that we can hide the inner details. Levels of Hiding the Data and
Methods which are Encapsulated.

We can implement Abstraction by using Following 4 keywords


1. Private.
2. Public.
3. Protected.
4. Global.
Private: The members with this abstraction are visible and accessible only with in the Encapsulation.
Public: The members with this abstraction are visible and accessible throughout the organization.
Protected: The members with this abstraction are visible and accessible not only with in the encapsulation and also in related
encapsulations (Inheritance concept).
Global: The members with this abstraction are visible and accessible throughout the Salesforce.com
Note:
1) Before data member and member method we have to specify abstraction.
2) At the Encapsulation level, as per the oops principles, Data must be hidden and Methods must be visible. So data must be
Private and methods must be Public.

Syntax:
Abstraction Data member;
Abstraction Member Method();

Example:
Class Student
{
Private Integer sno,tm;
Private String sname;
Private Decimal avg;
Public Total_Marks();
Public Avg_Marks();
}
3) INHERITANCE: Reusing the Data and Functionality in one Encapsulation for another Encapsulation.

Example:

Class Human
{
// Data Members
String Name, Color;
Private Integer Age, ,Height, Weight;
// Member methods
Public Walk();
Public Talk();
Public Sleep();
}

We can derive two sub classes i.e., Male Class and Female Class and every Male and Female Class.
Have same kind of data and method so that we no need to declare once again we can directly inherit from Human Class into
Male and Female class. This is called Inheritance.

4.POLYMORPHISM: Here POLY means Many, MORPH means Forms.

For ex: Restaurant, Functions, we can implement Polymorphism using following ways.

1. Method OverLoading.
2. Method Overriding : Generally we are walking in the direction of our face, but if somebody asking to walk backward
direction we can walk, but it is in different direction. So, When we change the mechanism of the function is called
overriding.
3. Operator OverLoading
4. Constructor Overloading

So, these are the 4 Key pillars of OOPs.

There are 3 places we can write the code, out of which 2 are cloud based and 1 are desktop based
Cloud based—within organization
1st way:
Setup builddevelopAppex Classes new button
2nd way:
Goto user nameDeveloper console filenew->apex class
Desktop
Eclipse it is an IDE (integrated development environment), it is a tool which gives 5 things
i.e Editor, Linker, compiler, library, console(takes input and gives output) , here programmer can
write the program in a single Environment.
So, we can also write our Apex programs in Eclipse tool but we need to add some plug in like
Force.com IDE it is the combination of Eclipse+force.com plug in

Structure of Apex program:

1) Every Apex program must be a class /Encapsulation


2) Apex Classes are classified into 2 types
We can write 2 types of classes in Apex
1. Business Class: this Class is used write to develop the application, and whatever definitions we discussed earlier that is
fit into this class, like blue print, user defined data type etc.,
2. Test Class: this class is used to write for test the behavior of business class.First we need to discuss with how to write Test class.
Test Class name is Demo Test
@isTest
Public class DemoTest{
}
Note: to distinguish between the test class and business class, test class always need starts with ‘@isTest’.
Test class we can execute but business class we cannot execute. Business class will be executed via test class.
To save and compile the test class or business class we need to type ctrl +S.

How to write a business class:


Public class ClassName{
Data members;
Member methods;
}
Note: first always we need to write business class then we need write test class.
Naming Conventions need to follow in OOPL:
1. How to write a class name: Every word first letter must be upper case.
Ex: if my class name is helloworld then we need write it as HelloWorld.
2. How to write a Method names: first word is lower case, there after every word first letter upper case. Ex: helloWorld().
3. How to write Constant names?
Completely Upper case ex: HELLOWORLD
4. How to write variable name?
Completely lower case  ex: helloworld
Note: why this way? Names are called identifiers, names are given by programmer. But how to identify these names?
Using Identifiers.

5. What type name to have


Class name name of the class relevant to real world existence
Method name
1. Create – Constructor name
2. Input -- setValues()
3. Process – name must be relevant to the action performed
4. Output – getValues()
Generally program execution starts from Main()  method in C,C++,Java .But in Apex code always executes starts from testMethod.
Main() is not the starting point of execution in apex, it could by any.
ARE Apex Runtime Engine looks for testMethod in the program and starts execution from there itself.
Note: testMethod we cannot write in Business Class, it must be in Test class only
If we remove @isTest from Test class and execute the program then it will show the following error msg “ defining type for testmethod
methods must be declared as IsTest”.
We can write multiple testmethods in test class .
Testmethods are executed in alphabetical order.
State of an object: Object state can change , setValue method can change state of the object and Whereas getValue method displays the
current state of the object.

Programs:

// 1. write an apex code input two number and print it.

Business Class:

public class MyClass{


Integer num1;
Integer num2;
public void input(integer x, integer y)
{
num1=x;
num2=y;
}

public void output()


{
System.debug('the value of a is ' + num1);
System.debug('the value of b is' + num2);

}
}

Test Class:

@isTest
public class MyclassTest {
public static testMethod void pain() {
MyClass obj= new MyClass();
obj.input(10,20);
obj.output();
}
}

//2. write an apex code input two number and find its sum and print it.

Business Class:

public class MyClass{


// Data Members
Integer num1;
Integer num2;
Integer result;
// Member Methods
// 1. Create
Public MyClass()
{
Num1=0;
Num2=0;
}
// input
public void input(integer x, integer y)
{
num1=x;
num2=y;
}

// process
Public void process()
{
Result = num1 + num2;
}
// output
public void output()
{
System.debug('the sum is ' + result);

}
}

3nd program: Input Student details and calculate total marks and average marks

Business Class:

public class studentClass{


// data members
Integer sno,marks1,marks2,marks3,total_marks;
String sname;
Decimal avg_marks;
// member methods
// constructor
// create
public studentClass() // constructor method defintion
{
sno=101;
sname='Raj';
marks1=0;
marks2=0;
marks3=0;
total_marks=0;
avg_marks=0.0;
}
// input
public void setValues(Integer sub1,Integer sub2, Integer sub3)
{
marks1=sub1;
marks2=sub2;
marks3=sub3;
total_marks=marks1+marks2+marks3;
avg_marks=total_marks/3;
}
// ouput
public void getValues()
{
System.debug('Student Number :' + sno);
System.debug('Student Name :' + sname);
System.debug('Marks in the First Subject :' + marks1);
System.debug('Marks in the Second Subjet : ' + marks2);
System.debug('Marks in the Third Subject :' + marks3);
System.debug('The total marks is ' + total_marks);
System.debug('The avg marks is ' + avg_marks);

}
}

Test Class:

@isTest
public class studentClassTest {
public static testMethod void main()
{
studentClass obj = new studentClass(); // calling point of constructor
// check the state of the values of the object
obj.setValues(90,90,90); // calling point
obj.getValues(); // calling point

}
}

Program 4: input employee details and calculate gross salary and net salary

Business Class:

public class empClass {


Integer empno,basic_sal,hra,da,pf,tax;
String ename;
Decimal gross,net_sal;
public empClass()
{
empno=101;
ename='Raj';
basic_sal=0;
hra=0;
da=0;
pf=0;
tax=0;
gross=0;
net_sal=0;
}
public void setVal(Integer bs,Integer hr,Integer d_a,Integer p_f, Integer t_x)
{
basic_sal=bs;
hra=hr;
da=d_a;
pf=p_f;
tax=t_x;
gross=basic_sal+hra+da;
net_sal=gross-(pf+tax);

}
public void getVal()
{
System.debug('Employee Id ' + empno);
System.debug('Employee Name ' + ename);
System.debug('Employee Gross Salary' + gross);
System.debug('Employee Net Salary' + net_sal);

}
}

Test Class:

@isTest
public class empClassTest {
public static testMethod void main(){
empClass obj = new empClass();
obj.setVal(15000,5000,2000,1000,500);
obj.getVal();
}
}

Program5: Input 2 number and find the biggest number

Business Class:

public class ifClass {


// data members
Integer num1;
Integer num2;
//member methods
// constructor method
public ifClass()
{
num1=0;
num2=0;
}
public void setVal(Integer x, Integer y)
{
Integer max;
num1=x;
num2=y;
if(num1>num2)
System.debug('Num1 is big');
else
if(num1==num2)
System.debug('Both are Equal');
else
System.debug('Num2 is big');
}
}

Test Class:

@isTest
public class ifCalssTest {
public static testMethod void main()
{
ifClass obj = new ifClass();
obj.setVal(10,10);
}
}

Program 6: Bank Class:

Business Class:

public class bankAccount {


// data members
Integer ac_no;
String ach_name;
Integer ac_bal;
// member methods
// 1. create
public bankAccount() // default constructor
{
System.Debug('I am default Constructor');
ac_no=0;
ach_name='no name';
ac_bal=0;
}
public bankAccount(Integer no, String name, Integer bal) // parameterized constructor
{
System.Debug('I am in parameterized constructor');
ac_no=no;
ach_name=name;
ac_bal=bal;

}
public void setValues(Integer no, String name, Integer bal) // parameterized constructor
{
ac_no=no;
ach_name=name;
ac_bal=bal;

public void getValues(){


System.debug('Acc no'+ ac_no);
System.debug('Name ' + ach_name);
System.debug('Balance is ' + ac_bal);
}
// 3. Process
// deposits
public void deposit(Integer amt)
{
ac_bal=ac_bal+amt;
}
//withdraw
public void withdraw(Integer amt)
{
ac_bal=ac_bal-amt;
}
// 4.output
public void checkBalance()
{
System.debug('the Balnace is ' + ac_bal);
}

Test Class

@isTest
public class bankAccountTest {
public static testMethod void main()
{
bankAccount bank1 = new bankAccount();
bank1.getValues();
bank1.setValues(101,'Raj',10000);
bank1.getValues();
bank1.deposit(15000);
bank1.checkBalance();
bank1.withdraw(5000);
bank1.checkBalance();

}
}

Program 7: Rectangle: calculate area and perimeter of a rectangle

Business Class
public class rectangleClass{
// data members
Integer length;
Integer breadth;
//create
public rectangleClass() // default constructor
{
Length=0;
Breadth=0;
}
public rectangleClass(Integer len, Integer bred)
{
length=len;
breadth=bred;

}
// input
Public void setValues(integer len,integer bred)
{
length=len;
breadth=bred;
}

//action or process
Public integer calcArea( )
{
Integer area;
area= length*breadth;
return area;
}
public integer calcPerimeter()
{
Integer perimeter;
perimeter=2*(length+breadth);
return perimeter;
}
}

Test Class

@isTest
public class rectangleClassTest{
public static testMethod void main()
{
// area of board calculation
rectangleClass board = new rectangleClass();
board.setValues(10,20);
integer ar_b=board.calcArea();
System.debug('Area of board ' + ar_b);

// area of keyboar calculation


rectangleClass keyboard = new rectangleClass(20,30);
integer ar_kb= keyboard.calcArea();
System.debug('Area of Keyboard is ' + ar_kb);

// perimeter of a board calcuation


board.setValues(40,50);
integer pr_b=board.calcPerimeter();
System.debug('Perimeter of a board is ' + pr_b);

// perimeter of a keyboard calculation


keyboard.setValues(60,70);
integer pr_kb=keyboard.calcPerimeter();
System.debug('Perimeter of a keyboad is ' + pr_kb);

Business Class: Changing parameter names in Parameterized constructor.

public class rectangleClass{


// data members
Integer length;
Integer breadth;
//create
public rectangleClass() // default constructor
{
Length=0;
Breadth=0;
}
public rectangleClass(Integer length, Integer breadth)
{
length=length;
breadth=breadth;

}
// input
Public void setValues(integer len,integer bred)
{
length=len;
breadth=bred;
}

//action or process
Public integer calcArea( )
{
Integer area;
area= length*breadth;
return area;
}
public integer calcPerimeter()
{
Integer perimeter;
perimeter=2*(length+breadth);
return perimeter;
}
public void getValues()

{
System.debug('The length is ' + length);
System.debug('The width is ' + breadth);

}
}

Test Class:
@isTest
public class rectangleClassTest{
public static testMethod void main()
{
RectangleClass box = new RectangleClass(12,18);
box.getValues();

}
}

Program 8: Even or Odd


Business Class:

public class EvenorOdd {


// data member
integer num1;

// member method
// create
public EvenorOdd()
{
num1=0;

}
// input
public void setValues( integer x)
{
num1=x;

}
// process
public integer EO()
{
if(math.mod(num1,2)==0)
return 0;
else
return 1;
}

Test Class:
@isTest
public class EvenorOddTest {
public static testmethod void main()
{
integer m1=0;
EvenorOdd obj= new EvenorOdd();
obj.setValues(10001);
m1=obj.eo();
if(m1==0)
system.debug('the given number is even');
else
system.debug('the given number is odd');

}
}

Program 9: Positive or Negative Test:


Busniess Class:

public class POorNEG {


// data member
integer num1;

// member method
// create
public POorNEG()
{
num1=0;

}
// input
public void setValues( integer x)
{
num1=x;

}
// process
public integer PN()
{
if(num1>0)
return 1;
else
if(num1==0)

return 0;
else
return -1;
}

Test Class:

@isTest
public class POorNEGTest {
public static testmethod void main()
{
integer m1=0;
POorNEG obj= new POorNEG();
obj.setValues(-10001);
m1=obj.PN();
if(m1==1)
system.debug('the given number is Postive');
else
if(m1==0)
system.debug('the given number is nuetral');
else
system.debug('the given number is negative');

}
}
Program 10: Student Pass or Fail Test

Business Class:
public class StudentPassOrFailClass {
String name;
integer id;
integer []marks;
public void acceptDetails(String name,integer id)
{
this.name=name;
this.id=id;
}
public void acceptMarks(integer []marks)
{
this.marks=marks;
}
public integer calculateTotalMarksAndDisplay()
{
integer total=0;

System.debug('MarksList:');

for(integer i=0;i<5;i++)
{
System.debug('Subject '+(i+1)+'='+marks[i]);
total=total+marks[i];
}
return total;
}
public decimal calculatePercentage()
{
integer total=calculateTotalMarksAndDisplay();
System.debug('Total Marks ='+total);
decimal per=total/5;
return per;

public boolean checkPassFail()


{
boolean status=true;
for(integer i=0;i<5;i++){
if(marks[i]<35){
status=!(true);
}

}
return status;
}
public void displaystudentReportCard()
{ System.debug('Id:'+id);
System.debug('Name:'+name);
decimal per=calculatePercentage();
if(checkPassFail()){
System.debug('Percentage:'+per);
if(per>=70)
System.debug('Grade:A+ Destinction');
else if(per>=50 &&per<70)
System.debug('Grade:A First Class');
else if(per>=40 && per<50)
System.debug('Grade:B Second Class');
else
System.debug('Grade:c Third Class');
}
else
System.debug('Result:Fail');
}

Test Class:
@isTest
public class StudentPassOrFailClassTest {
public static testmethod void studentDetails()
{
StudentPassOrFailClass info = new StudentPassOrFailClass();
info.acceptDetails('samreen', 402);
integer []marks=new integer[]{100,90,90,90,100};
info.acceptMarks(marks);
info.displaystudentReportCard();

}
}

Program 11: Static Method Bank Account

Business Class:

public class BankAccount {


// data members
Integer ac_no;
String ach_name;
Integer ac_bal;
static Integer count=0;

// member methods
// 1. create
public bankAccount() // default constructor
{
System.Debug('I am default Constructor');

ac_no=0;
ach_name='no name';
ac_bal=0;
count++;
}
/* public bankAccount(Integer no, String name, Integer bal) // parameterized constructor
{
System.Debug('I am in parameterized constructor');
ac_no=no;
ach_name=name;
ac_bal=bal;

} */
public void setValues(Integer no, String name, Integer bal)
{
ac_no=no;
ach_name=name;
ac_bal=bal;

public static void getCount()


{

System.debug('the numbe of objects are created ' + count);


}
public void getValues(){
System.debug('Acc no'+ ac_no);
System.debug('Name ' + ach_name);
System.debug('Balance is ' + ac_bal);
}
// 3. Process
// deposits
public void deposit(Integer amt)
{
ac_bal=ac_bal+amt;
}
//withdraw
public void withdraw(Integer amt)
{
ac_bal=ac_bal-amt;
}
// 4.output

public void checkBalance()


{
System.debug('the Balnace is ' + ac_bal);
}

Test Class:

@isTest
public class bankAccountTest {
public static testMethod void main()
{
BankAccount bank1 = new BankAccount();
bank1.getValues();
bank1.setValues(101,'Raj',10000);
bank1.getValues();
bank1.deposit(15000);
bank1.checkBalance();
bank1.withdraw(5000);
bank1.checkBalance();
BankAccount.getcount();
bankAccount bank2 = new bankAccount();
bank2.getValues();
bank2.setValues(102,'Ram',20000);
bank2.getValues();
bank2.deposit(5000);
bank2.checkBalance();
bank2.withdraw(10000);
bank2.checkBalance();
BankAccount.getcount();
}
}

Program 12: Method OverLoading

public class MethodOverLoading {


// datamembers
Integer num1;
Integer num2;
Integer num3;
Integer num4;
// member methods
// create
// default constructor
public MethodOverLoading()
{
num1=0;
num2=0;
num3=0;
num4=0;
}
// input
public integer setValues(Integer a, Integer b)
{
integer x;
num1=a;
num2=b;
x=num1+num2;
return x;
}
public integer setValues(Integer a, integer b, integer c)
{
integer x;
num1=a;
num2=b;
num3=c;
x=num1+num2+num3;
return x;
}
public integer setValues(Integer a, Integer b, Integer c , Integer d)
{
integer x;
num1=a;
num2=b;
num3=c;
num4=d;
x=num1+num2+num3+num4;
return x;
}
}

Test Class:

@isTest
public class MethodOverLoadingTest {
public static testMethod void main()
{
MethodOverLoading obj = new MethodOverLoading();
Integer first =obj.setValues(10,20);
System.debug('the sum of two numbers is' + first);
integer second=obj.setValues(10,20,30);
System.debug('the sum of three numbers is' + second);
Integer third=obj.setValues(10,20,30,40);
System.debug('the sum of four numbers is' + third);
}
}

Exception Handling:

OBJECTIVES:
In this is Chapter you will learn
Learn what an Exception is.
What is an Error.
Types of Errors.
Learning how to handle Exceptions in a Program.
Learning Exception handling through Try/Catch.
High level language(source code)----Intermediate code---Machine Level Language – run—output

SYNTACTICAL ERRORS—if the programmer do not follow the language rules and regulations then it will display syntactical errors.
These errors will raise at the time converting program from HLL to IC.

If high level language code successfully converted into intermediate code then it fails to convert into Machine level language code then it
will display ‘SEMANTICAL ERRORS’.

Semantical Errors: There is no meaning in the statement.

num1,num2,result integer;

12+16==82

if the program successfully converts from HLL – IC –MLL – RUN – Output wrong – BUG.

1. Syntactical Errors—fails to convert from HLL to IC


2. Semantical Errors – IC-- MLL
3. Bug—run –Wrong output
4. We do not get any output --- Exception

DEFINITION:
“It is a Mechanism of designing the code which enables the processing of the Program to continue inspite of the Occurrence of the Run-
Time Error”
What is an Error?
An Error is a condition where the processing of the program gets terminated automatically.
Types of Errors:
There are 2 types of Error.
1. Translation Error:
Here the Error occurs in the translation phase of the program. Translation Error is of two types.
i. Syntax error
ii. Symatic error.
Syntax Error and symantic error are the Rules to create the statements. The only one way to overcome these errors is to change the
source code.
2. Execution Error.
This Error occurs at the execution phase of the program, these are known as runtime error or Exception.
Exception Handling can be achieved through two keywords.
1. Try
2. Catch.

TYPES:
Built-In Exceptions and Common Methods:
Dml Exception:
Any problem with a DML statement, such as an insert statement missing a required field on a record.
This example makes use of Dml Exception. The insert DML statement in this example causes a Dml Exception because it’s inserting a
merchandise item without setting any of its required fields. This exception is caught in the catch block and the exception message is
written to the debug log using the System. Debug statement.

Exception Handling
Convert system defined error msgs into User Defined error msgs.
We can handle exceptions by using Try and Catch methods.

What Happens 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.
SYNTAX:
The below is the Syntax for the Exception Handling which includes Try and catch.
Try {
Statements which gives the runtime error.
}
Catch {
These are the statements that notify the Exception.
}.

1. Null Pointer Exception: this exception will raise when the user trying to perform operations o n null values.

@isTest
public class nullpointer {
public static testmethod void main()
{
integer num1,num2,result;
try{
result = num1+num2;
}
catch(exception c)
{
system.debug('Sorry we cannot perform addition operation on null values');
}
num1=10;
num2=20;
result = num1+num2;
system.debug('the result is ' + result);
}

2. Arithmatic Exception: This exception will raise when the user trying to dividing the number by zero.

ARITHMATIC EXCEPTION:

@isTest
Public class arithMatic{
Public static testmethod void main()
{

Integer num1,num2,result;
Num1=10;
Num2=0;
Try{
Result= num1/num2;
}
Catch{
System.debug(‘sorry we cannot divide the number by zero’);
}
}

3. Array out of bound Exception: This exception will raise when the user trying to fetch element out of the array size.

3 Array out of Bound Exception:


@isTest
Public class arrayOutofBound{
Public static testmethod void main()
{
Integer [] a = new integer[5];
A[0]=10;
A[1]=30;
A[2]=40;
A[3]=90;
A[4]=100;
Try{
System.debug(a[14]);
}
Catch{
System.debug(‘there Is no element in the 14 index ‘);
}
}

Assertions: There is close relation between Exception and Handling and Assertion, ie.

In exception handling if any problem occurs then control takes another path and executes the rest of the statements but where as in
assertion if any problem get occurs then the control completely comes of the program.

1. System.assert()
2. System.assertEquals()
3. System.assertNotEquals()

@isTest

public class Assert {

public static testmethod void main()

integer num1,num2,result;

num1=10;

num2=10;

/* if condition is true, then it will executes the statements,if it is false then error

message will be displayed */

// system.assert(num2!=0,'sorry we cannot divide number by zero');

// system.assertEquals(num2,10,'Sorry we cannot divide');

system.assertNotEquals(num2,0,'not possible to divide');

result=num1/num2;

system.debug('the result is '+ result) ;

}
}

Annotation:

1. Annotations are special words in a language and always begins with “@” symbol.
2. These words convey a special meaning to the server in order to treat a resource differently.
3. Apex provided many annotations such as @isTes,@future,@depricated etc,

1 @isTest Defines classes that only contain code used for


testing your application. These classes don’t count
against the total amount of Apex used by your
organization.

2 @deprecated Identifies methods, classes, exceptions,


enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed
package in which they reside.
Eg:
@deprecated
public void method () {
}

3 @readOnly Defines methods that can perform queries unrestricted by the number of returned rows limit for a
request.

4 @future Identifies methods that are executed asynchronously.

Eg: global class MyFutureClass {


@future
static void myMethod(String a, Integer i) {
System.debug( ‘Method called with: ‘ + a + ‘ and ‘ + i);
// do callout, other long
// running code
}
}

5 @httpGet, Defines a REST method in a class annotated with


@httpPost, @httpPatch, @restResource that the runtime invokes when a client sends an HTTP GET, POST, PATCH, PUT, or
@httpPut, @httpDelete DELETE respectively. The methods defined with any of these annotations must be global and static.
Syntax:
@httpGet
global static MyWidget__c doGet() {
}
@httpPost
global static void doPost() {
}
@httpDelete
global static void doDelete() {
}

6 @restResource Identifies a class that is available as a REST resource. The class must be global. The urlMapping
parameter is your
resource’s name and is relative to https://instance.salesforce.com/services/apexrest/
Syntax:
@restResource(urlMapping= ‘/Widget/*’)
global with sharing class MyResource() {
}

Main()

------

--------

----
Abc();

Abc()

--

--

Pqr();

--

--

Pqr()

--

--

public class Annotation{

public void FirstMethod()

system.debug('i am in first method starting');

SecondMethod();

system.debug('i am in First method ending');

@future

public static void SecondMethod()

system.debug('i am in Second method starting');

system.debug('i am in Second method ending');

Test class:

@isTest
public class AnnotationTest {

public static @isTest void main()

Annotation obj = new Annotation();

obj.FirstMethod();

SOQL: It stands for Salesforce Object Query Langauge, which Is used to communicate with the database.

This language contains only one command i.e Select

Select : Using this command we can fetch the data from sobject.

Using this command we can fetch all the records in the subject and also we can fetch specific records in the sobject.(using Where
Clause).

Syntax:

Select col1,col2…..coln from <sobject>;

Ex:

Select name,ename__c,salary__C,deptno__C from employee__c;

Using this command we can fetch the data in 3 ways

1. Projection 2. Selection 3. Joins

Projection: Retrieve the data from specific columns in the sobject.

Syntax:

Select name,ename__c from employee__c;

2. Selection: Retrieve the data based on some condition using where clause.

Select col1,col2…..coln from <sobject> where <condition>;

Ex:

Select name,ename__c,salary__C,deptno__C from employee__c where ename=’uma’;

Queries:

1. Display the employee details who are working in 10 and 20;


Select name,ename__c,salary__C,deptno__C from employee__c where deptno__c =10 or deptno__c=20
2. Display the employee details whose name is prakash
Select name,ename__c,salary__c,deptno__C from employee__c where ename__c=’prakash’
3. Display the employee details whose salary between 50000 and 90000.
Select name,ename__c,salary__c,deptno__C from employee__c where salary__c>=50000 and
Salary__C<=90000
4. Display the employee details who are not working in 20 deptno.
Select name,ename__c,salary__c,deptno__C from employee__c where deptno__c !=20
5. Display the employee details whose employee number is 1001
Select name,ename__c,salary__c,deptno__C from employee__c where name=e’-1001’

1. Display the employee details whose name contains only 5 letters


2. Display the employee details whose name starts with S
3. Display the employee details who are not working under 10 and 30
4. Display the employee details whose salary not between 50000 and 90000
5. Display the employee details whose name contains letter A

Order by Clause:

This clause is used to arrange the records in a proper order i.e either ascending or descending order

By default order by clause will arrange the records in ascending order , if we want to arrange the records

In descending order then we need to use an option called desc.

We can apply the order by clause on any column in the sobject.

If we apply the order by clause on character column then it will arrange the records in alphabetical order.

We can apply the order by clause on more than one column in the same sobject.

Syntax:

Select col1,col2……coln from <sobject> order by <column name>;

Ex:

Select name,ename__c,salary__c,deptno__c from employee__c order by name

select name,ename__c,salary__C,deptno__C from employee__c order by ename__c,salary__c

select name,ename__c,salary__C,deptno__c from employee__c order by deptno__c nulls last

where – order by clause:

select name,ename__c,salary__C,deptno__c from employee__c where deptno__C=10 or deptno__C=20 order by name

functions

group by

cube

rollup

having

limit

Das könnte Ihnen auch gefallen