0% found this document useful (0 votes)
36 views12 pages

Primitive Data Types and Variables:: Example

This document provides an overview of various data types, variables, and key programming concepts in Apex such as strings, booleans, dates, times, numbers, null values, enums, lists, sets, maps, classes, objects, methods, interfaces, SOQL, and DML operations. It defines each data type and provides examples of how to declare and use variables of those types. It also explains concepts like conditional statements, loops, and how to work with objects and the Salesforce database.

Uploaded by

Poornachander
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views12 pages

Primitive Data Types and Variables:: Example

This document provides an overview of various data types, variables, and key programming concepts in Apex such as strings, booleans, dates, times, numbers, null values, enums, lists, sets, maps, classes, objects, methods, interfaces, SOQL, and DML operations. It defines each data type and provides examples of how to declare and use variables of those types. It also explains concepts like conditional statements, loops, and how to work with objects and the Salesforce database.

Uploaded by

Poornachander
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Primitive Data Types and Variables:

Following are the data types and variables in Apex:

 String
 Boolean
 Time, Date and Datetime
 Integer, Long, Double and Decimal
 Null Variables
 Enum

String:
Example:
String myVariable = 'I am a string.';

 We can also create String from value of other data type. It can be done using static
method valueOf()

Example:
1. Date myDate = Date.today();
String myString = String.valueOf(myDate);
System.debug(myString);

2. Integer myInt = Integer.valueOf('123');


The + operator acts as a concatenation operator when applied to strings.

Methods in String:
1. endsWith(suffix):
Example:
String s = 'Hello Jason';
System.debug(s.endsWith('Jason'));
2. length():
Example:
String myString = 'abcd';
Integer result = myString.length();
System.assertEquals(result, 4);
3. substring(startIndex, endIndex):
Returns a new String that begins with the character at the specified zero-
based startIndex and extends to the character at end Index - 1.
Example:
'hamburger'.substring(4, 8);
// Returns "urge"

'smiles'.substring(1, 5);
// Returns "mile"

Boolean and Conditional Statements: returns true or false


EscapeSequences:
\b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double
quote), \' (single quote), and \\ (backslash).

Time, Date and Datetime:


Example:
Date myDate = Date.newinstance(1960, 2, 17);
Time myTime = Time.newInstance(18, 30, 2, 20);
System.debug(myDate);
System.debug(myTime);
Output:

1960-02-17 00:00:00
18:30:02.020Z
Example2:

//You can also create dates and times from the current clock:

Datetime myDateTime = Datetime.now();


Date today = Date.today();
Example3:

Datetime has the addHours, addMinutes, dayOfYear, timeGMT methods and many others.
Date myToday = Date.today();
Date myNext30 = myToday.addDays(30);
System.debug('myToday = ' + myToday);
System.debug('myNext30= ' + myNext30);

Integer, Long, Double and Decimal


Example:
Double d = 3.14159;
Decimal dec = 19.23;
Integer countMe = Integer.valueof('10') + 20;

//Rounding behaviour of decimals


Decimal decBefore = 19.23;
Decimal decAfter = decBefore.Divide(100, 3);
System.debug(decAfter);
Output: The value of decAfter will be set to 0.192.

Null Variables:
Variable value will be set to null if we don’t initialise it.

Enums:
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.
To define an enum, use the enum keyword in your declaration and use curly braces to
demarcate the list of possible values.
public enum Season {WINTER, SPRING, SUMMER, FALL}

Case Sensitivity:
Apex is case insensitive language
Lists:
Ordered group of items of same type.

Declaring a list with set size:


Stirng[] x= new String[4];

Conditional Statements:
If-else statements:
if(condition is true) {
//do this
} else {
//do this
}

Switch Statements:
switch on expression {
when value1 {
//code block 1
}
when value2 {
//code block 2
}
when else { //if none of the previous values apply
//code block 3
}
}

Loops:
While loops:

Syntax:
While(condition) {
//run this block of code
}

Do While Loops:
Syntax:
Do {
//run this block of code
} while(condition);

For loops:
//normal loop
for (Integer i = 1; i <= 10; i++){
System.debug(i);
}
//loop iterating over a list:
Integer[] myInts = new Integer[]{10,20,30,40,50,60,70,80,90,100};
for (Integer i: myInts)
{
System.debug(i);
}

Sets:
Unordered collection of objects and doesn’t contain duplicate values
Set s = new Set{'a','b','c'};

// Because c is already a member, nothing will happen.

s.add('c');

s.add('d');

if (s.contains('b'))

System.debug ('I contain b and have size ' + s.size());

Maps:

Contains key value pairs

Example:
Map <integer, String> employeeAddresses = new Map<integer, String();

employeeAddresses.put (1, '123 Sunny Drive, San Francisco, CA');

employeeAddresses.put (2, '456 Dark Drive, San Francisco, CA');

System.debug('Address for employeeID 2: ' + employeeAddresses.get(2));

Map<String,String> myStrings = new Map{'a'=>'apple','b'=>'bee'};

System.debug(myStrings.get('a'));

Classes and Objects in apex:


A class is a blue Print
A class defines a set of characteristics and behaviours that are common to all objects of that
class.
//Declaring a class

Methods
A method can be declared as
Example:
wilt(4);
public static void wilt(Integer numberOfPetals){
system.debug(numberOfPetals);
}

Example:
public class Flower {
public static Integer wilt(Integer numberOfPetals){
if(numberOfPetals >= 1){
numberOfPetals--;
}
return numberOfPetals;
}
public static void grow(Integer height, Integer maxHeight){
height = height + 2;
if(height >= maxHeight){
pollinate();
}
}
public static void pollinate(){
System.debug('Pollinating...');
}
}
Static variables:
We can access static variables without instantiating the calss.
Final variable:
We cannot change the value of final variable once declared.
We can pass object as argument as follows
public static void toDebug(Fridge aFridge) {

System.debug ('ModelNumber = ' + aFridge.modelNumber);

System.debug ('Number in Stock = ' + aFridge.numberInStock);

Interfaces:
Interfaces is used for abstraction
Interfaces don’t have any implementations
//Creating an interface
public interface InterfaceName{
String method();
}
Implements is the method used to overload the method form an interface.

Sobjects and Databases:


An sObject is an Apex data type that corresponds to a Salesforce object (sObject) in an org.
sObjects are complex data types that hold multiple values in one variable. They hold a single
record of data from a Salesforce object, such as an Account, a Contact, or an Opportunity.

Example:
public class NewAccounts {
public static void sObjectsInsert(Integer value){
Integer counter = 1;
//create a list to add our accounts
List<Account> teaFactoryAccounts = new List<Account>();
while(counter <= value){
//display the current counter value
System.debug('Counter Value before Incrementing ' + counter);
//create a new account
Account store = new Account();
store.Name = 'The Tea Factory ' + counter;
store.AccountNumber = '35629' + counter;
teaFactoryAccounts.add(store);
System.debug(teaFactoryAccounts);
//increment the counter
counter = counter + 1;
System.debug('Counter Value after incrementing ' + counter);
}
System.debug('Size of Account List: ' + teaFactoryAccounts.size() );
System.debug('Elements in Account List: ' + teaFactoryAccounts);
//insert all of the accounts in the list
insert teaFactoryAccounts;
}
}

SOQL:

SOQL clauses:
Example:
public class AccountUtility {
public static void viewAnnualRevenue(){
List<Account> accountsList = [SELECT Name, AnnualRevenue FROM Account];
for (Account con : accountsList){
String acctRev = con.Name + ':' + con.AnnualRevenue;
system.debug(acctRev);
}

}
}

Relationship queries with Standard Objects:

To get records for a:

 Child object, and include fields from a related parent object, use a child-to-
parent query.
 Parent object, and include fields from a related child object, use a parent-to-
child query.

Child to Parent query example:


SELECT Name, Account.Name FROM Contact
Parernt to child query:
DML commands:
Insert
Update
Delete
Undelete

You might also like