SFDC Stop - Always the latest about Salesforce


Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.


Telegram logo   Join our Telegram Channel
Showing posts with label Data Types. Show all posts
Showing posts with label Data Types. Show all posts

Tuesday, 6 August 2024

Collections in Apex - Salesforce Apex Tutorial Part 8 to 13 | Code Snippet

Hello Trailblazers,


In this post, I'm sharing the code snippet for Coding with Confidence: The Fun Way to Learn Salesforce Apex tutorial series part 8 and above below:
// * Collections in Apex

/*
*   There are 3 types of collections in apex:
*   1. List
*   2. Set
*   3. Map
*/

// * List - Part 1

// * List: A list is an ordered collection of elements. We can create a list of any data type like: primitive data types, collections, sObjects, custom data types etc.

// * Creating a list of names
List<String> names = new List<String>();
names.add('Richard Hendricks');
names.add('Monica');
names.add('Erlich Bachman');
names.add('Dinesh');
names.add('Gilfoyle');

System.debug('Names = ' + names);

// * Retrieving an element from the list
System.debug('Element at index 2 = ' + names[2]);

// * Replacing a list element at a particular index
names.set(2, 'Gavin Belson');
System.debug('Updated Names = ' + names);

names[2] = 'Erlich Bachman';
System.debug('Updated Names = ' + names);

// * Setting an index that doesn't exist
// names.set(10, 'Jared Dunn');

// names[10] = 'Jared Dunn';

// * Displaying the size of the list
System.debug('Size of list "names" = ' + names.size());

// * Clearing the list
names.clear();

System.debug('Size of list "names" = ' + names.size());
System.debug('Updated Names = ' + names);

// * List - Part 2

// * Checking if the list is empty
List<Integer> numbers = new List<Integer>();
System.debug('Numbers List = ' + numbers);
System.debug('Numbers List is empty = ' + numbers.isEmpty());

numbers.add(1);
numbers.add(2);

System.debug('Numbers List = ' + numbers);
System.debug('Numbers List is empty = ' + numbers.isEmpty());

// * Defining lists using array notation
String[] names = new String[5];
// List<String> names = new String[5];
// String[] names = new List<String>();
names[2] = 'Gavin Belson';
names[4] = 'Jared Dunn';
names[0] = 'Richard Hendricks';
names[1] = 'Erlich Bachman';
names[3] = 'Monica';
// names.add('Gavin Belson');
System.debug('Names Array = ' + names);
System.debug('Size of list "names" = ' + names.size());

// names[5] = 'Dinesh Chugtai';

names.add('Dinesh Chugtai');

System.debug('Updated Names = ' + names);
System.debug('Size of list "names" = ' + names.size());

// * Populating values inside a list at the time of initialization
List<String> names = new List<String>{'SFDC Stop', 'Rahul Malhotra'};
System.debug('Initial Names = ' + names);

String[] names = new String[]{'SFDC Stop', 'Rahul Malhotra'};
System.debug('Initial Names = ' + names);

// * List - Part 3

// * Sorting a list
List<String> names = new List<String>{'Richard Hendricks', 'Erlich Bachman', 'Gavin Belson', 'Monica', 'Jared Dunn', ''};
System.debug('Names = ' + names);
names.sort();
System.debug('Names in ascending order = ' + names);

// * Creating a list of collections
List<List<String>> names = new List<List<String>>(); // * Upto 8 levels
names.add(new List<String>{'Aman', 'Ashish', 'Adam', 'Anika'});
names.add(new List<String>{'Bob', 'Bhanu', 'Blake', 'Benjamin'});
System.debug('Names = ' + names);
System.debug('Names starting with "A" = ' + names[0]);
System.debug('Names starting with "B" = ' + names[1]);
System.debug('2nd name starting with "A" = ' + names[0][1]);
System.debug('3rd name starting with "B" = ' + names[1][2]);

// * Set

// * Set: A set is an unordered collection of elements that do not contain any duplicates. We can create a set of any data type like: primitive data types, collections, sObjects, custom data types etc.

// * Creating a set of integers
Set<Integer> numbers = new Set<Integer>();
numbers.add(2);
numbers.add(1);
numbers.add(4);
numbers.add(5);
numbers.add(3);

System.debug('Numbers Set = ' + numbers);
System.debug('Number of elements in Set = ' + numbers.size());

// * Adding duplicate elements inside set
numbers.add(1);
numbers.add(5);

System.debug('Numbers Set after adding duplicate elements = ' + numbers);
System.debug('Number of elements in Set = ' + numbers.size());

// * Check if 3 is present in set
System.debug('Is 3 present inside set = ' + numbers.contains(3));

// * Removing 3 from set
System.debug('Removing 3 from set...');
numbers.remove(3);

// * Check if 3 is present in set
System.debug('Is 3 present inside set = ' + numbers.contains(3));

System.debug('Numbers Set after removing 3 = ' + numbers);
System.debug('Number of elements in Set = ' + numbers.size());

// * Populating values inside a set at the time of initialization
Set<String> fruits = new Set<String>{'Mango', 'Apple', 'Banana', 'Pear', 'Mango'};
System.debug('Elements inside set of fruits = ' + fruits);

// * Map - Part 1

// * Map: A map is a collection of key-value pairs where each unique key maps to a single value. Keys and Values inside a map can be of any data type like: primitive data types, collections, sObjects, custom data types etc.

// * Creating a map of Integer, String:

Map<Integer, String> studentsMap = new Map<Integer, String>();
studentsMap.put(3, 'Gilfoyle');
studentsMap.put(5, 'Monica');
studentsMap.put(1, 'Richard Hendricks');
studentsMap.put(2, 'Dinesh');
studentsMap.put(4, 'Erlich Bachman');
studentsMap.put(null, 'Jared Dunn');

System.debug('Value of studentsMap = ' + studentsMap);
System.debug('Total number of elements inside studentsMap = ' + studentsMap.size());

// * Getting value from a map
System.debug('Student with roll number 3 = ' + studentsMap.get(3));

// * Updating value inside a map
System.debug('Assigning a new name to roll number 3');
studentsMap.put(3, 'Gavin Belson');

System.debug('Student with roll number 3 = ' + studentsMap.get(3));
System.debug('Value of studentsMap = ' + studentsMap);

// * Removing value from a map
studentsMap.remove(3);
System.debug('Value of studentsMap after removing student with roll number 3 = ' + studentsMap);
System.debug('Total number of elements inside studentsMap = ' + studentsMap.size());

// * Map - Part 2

Map<Integer, String> studentsMap = new Map<Integer, String>();
studentsMap.put(5, 'Monica');
studentsMap.put(1, 'Richard Hendricks');
studentsMap.put(2, 'Dinesh');
studentsMap.put(4, 'Erlich Bachman');
studentsMap.put(null, 'Jared Dunn');

// * Check if the map contains a key
System.debug('Does studentsMap contain roll number 4? ' + studentsMap.containsKey(4));
System.debug('Does studentsMap contain roll number 3? ' + studentsMap.containsKey(3));

System.debug('Value of studentsMap = ' + studentsMap);
System.debug('Total number of elements inside studentsMap = ' + studentsMap.size());

// * Check if map is empty
System.debug('Is student map empty? ' + studentsMap.isEmpty());

// * Remove all elements from the map
System.debug('Clearing elements inside studentsMap...');
studentsMap.clear();

// * Check if map is empty
System.debug('Is student map empty? ' + studentsMap.isEmpty());

System.debug('Value of studentsMap = ' + studentsMap);
System.debug('Total number of elements inside studentsMap = ' + studentsMap.size());

// * Getting KeySet and Values from the map
Map<Integer, String> studentsMap = new Map<Integer, String>();
studentsMap.put(1, 'Richard Hendricks');
studentsMap.put(2, 'Dinesh');
studentsMap.put(3, 'Gilfoyle');
studentsMap.put(4, 'Erlich Bachman');
studentsMap.put(2, 'Monica');
studentsMap.put(6, 'Dinesh');

System.debug('Value of studentsMap = ' + studentsMap);
System.debug('Total number of elements inside studentsMap = ' + studentsMap.size());

Set<Integer> keys = studentsMap.keySet();
System.debug('Keys of studentsMap = ' + keys);

List<String> studentNames = studentsMap.values();
System.debug('Values of studentsMap = ' + studentNames);

YouTube Tutorials

You can check out the tutorials below as well:

Apex Lists: Master List Manipulation - Part 1 | Apex Collections - Salesforce Apex Tutorial Part 8

Apex Lists: Master List Manipulation - Part 2 | Apex Collections - Salesforce Apex Tutorial Part 9


Apex Lists: Master List Manipulation - Part 3 | Apex Collections - Salesforce Apex Tutorial Part 10

Master Apex Sets: A Concise Guide | Apex Collections - Salesforce Apex Tutorial Part 11

Unlock the power of maps in Apex! 🗺️ - Part 1 | Apex Collections - Salesforce Apex Tutorial Part 12

Unlock the power of maps in Apex! 🗺️ - Part 2 | Apex Collections - Salesforce Apex Tutorial Part 13


Check out the tutorials and let me know your feedback in the comments down below.

Happy Trailblazing!!

Thursday, 25 April 2024

Building Blocks of Apex: Variables & Data Types Explained Simply - Salesforce Apex Tutorial Part 2 to 7 | Code Snippet

Hello Trailblazers,

In this post, I'm sharing the code snippet for Coding with Confidence: The Fun Way to Learn Salesforce Apex tutorial series part 2 to 7 below:
// * Variables & Data Types in Apex

/*

? What is a variable?
* A variable is simply a named storage/memory location that contains a value. In apex, all variables have a "data type".
! Each variable is by default initialized to null

? What is a Data Type?
* Data type is a keyword associated with a variable. It basically represents the type of data which that variable will store.
* List of primitive data types:
* 1. Boolean
* 2. Integer
* 3. Decimal
* 4. Double
* 5. Long
* 6. Date
* 7. Datetime
* 8. Time
* 9. Id
* 10. String
* 11. Object
* 12. Blob

* These are the OOTB or fundamental data types available in apex programming language. Let's talk about each one of them in detail:

? What is a Boolean data type?
* A variable of Boolean data type can store only one of these two values:
* 1. True
* 2. False

* Example of Boolean data type:
*/

/*
one
two
three

*/

// comment

// * In order to declare a variable, we follow the format: <Data Type><space><Variable name><;>
Boolean isQualified;
System.debug('Value of isQualified boolean variable is: ' + isQualified);

isQualified = false; // * Equals (=) means Assignment
System.debug('Value of isQualified boolean variable is: ' + isQualified);

isQualified = true;
System.debug('Value of isQualified boolean variable is: ' + isQualified);

// isQualified = 123;

/*

? What is an Integer data type?
* An Integer data type can store a 32-bit number with no decimal point. It can store value between -2,147,483,648 to 2,147,483,647

* Example of Integer data type:

*/

Integer sum;
System.debug('Value of sum Integer variable is: ' + sum);

sum = 1;
System.debug('Value of sum Integer variable is: ' + sum);

sum = 10;
System.debug('Value of sum Integer variable is: ' + sum);

sum = 2147483647;
System.debug('Value of sum Integer variable is: ' + sum);

sum = -2147483647;
System.debug('Value of sum Integer variable is: ' + sum);

// sum = false;

/*

? What is a Decimal data type?
* A Decimal data type variable can store a number with a decimal point.

* Example of Decimal data type:

*/

Decimal sum;
System.debug('Value of sum Decimal variable is: ' + sum);

sum = 1.0;
System.debug('Value of sum Decimal variable is: ' + sum);

sum = 1.01;
System.debug('Value of sum Decimal variable is: ' + sum);

sum = 1.234567890123456789012345678901234567890123456789;
System.debug('Value of sum Decimal variable is: ' + sum);

sum = -123456789012345678901234567890123456789012345678.9;
System.debug('Value of sum Decimal variable is: ' + sum);

//* Help Article about the field: https://help.salesforce.com/s/articleView?id=000387302&type=1, however we can have 49 digits in total for a variable of type decimal

// * Assiging integer to a decimal
sum = 123;
System.debug('Value of sum Decimal variable is: ' + sum);

// sum = true;

/*
? What is a Double data type?
* A Double data type variable can store a 64-bit number with a decimal point. It can store value between -2^63 to 2^63-1
* Example of Double data type:
*/

Double sum = 3.14;
System.debug('Value of sum Double variable is: ' + sum);

// * Use Double for less precision. For example: Scientific calculations where rounding off can be done. Use Decimal for more precision. For example: Financial calulations where there are no chances of errors. By default, currency fields in Salesforce are stored as decimals.

/*
? What is a Long data type?
* A Long data type variable can store a 64-bit number without a decimal point. It can store value between -2^63 to 2^63-1.
* Example of Long data type:
*/

Long long1 = 1000000000;  // * Valid long value without "L"
Long long2 = 9223372036854775807L;  // * Valid long value with "L" (for clarity)
System.debug('Value of long1 Long variable is: ' + long1);
System.debug('Value of long2 Long variable is: ' + long2);

// * Long can be used when we need a higher range as compared to an integer

/*
? What is a Date data type?
* A Date data type variable can store a date value without any information about time.
* Example of Date data type:
*/

Date date1 = Date.newInstance(1994, 12, 26);
System.debug('Value of date1 Date variable is: ' + date1);
System.debug('Subtracting 1 from date1 variable. Updated value = ' + (date1 - 1));
System.debug('Adding 1 to date1 variable. Updated value = ' + (date1 + 1));

Date dateFromString = Date.valueOf('1994-12-26');
System.debug('Value of dateFromString Date variable is: ' + dateFromString);

System.debug('Date in string without timestamp is: ' + String.valueOf(dateFromString));

System.debug('Today\'s Date is: ' + System.today());

// * Adding two date values
Date date1 = Date.newInstance(1994, 12, 26);
Date date2 = Date.newInstance(1994, 12, 20);
System.debug(date1 + date2);

/*
? What is a Datetime data type?
* A Datetime data type variable can store a datetime value like a timestamp.
* Example of Datetime data type:
*/

Datetime date1 = Datetime.newInstance(1994, 12, 26);
System.debug('Value of date1 Datetime variable is: ' + date1);

Datetime dateFromString = Datetime.valueOf('1994-12-26 23:11:10'); // GMT + 5:30
System.debug('Value of dateFromString Datetime variable is: ' + dateFromString);

System.debug('Date in string without timestamp is: ' + String.valueOf(dateFromString));

/*
? What is a Time data type?
* A Time data type variable can store a time value which indicates a particular time.
* Example of Time data type:
*/

Time time1 = Time.newInstance(14, 25, 60, 100);
System.debug('Value of time1 Time variable is: ' + time1);
System.debug('Value of hour: ' + time1.hour());
System.debug('Value of minute: ' + time1.minute());
System.debug('Value of second: ' + time1.second());
System.debug('Value of millisecond: ' + time1.millisecond());

/*
? What is a ID data type?
* An ID data type variable can store any valid 18-character salesforce record id.
* Example of ID data type:
*/

Id accountId = '001Hy00001D07fwIAB';
System.debug('Value of Id accountId = ' + accountId);

Id accountIdFifteenDigits = '001Hy00001D07fw';
System.debug('Value of Id accountIdFifteenDigits = ' + accountIdFifteenDigits);

accountId = '123456789123456789';

/*
? What is a String data type?
* A String data type variable can store any set of characters surrounded by single quotes. It has no limit on the number of characters, heap size limit is used instead
* Example of String data type:
*/

String name = 'SFDC Stop';
System.debug('Value of String name = ' + name);

String nameWithTrailingWhitespace = 'SFDC Stop   ';
System.debug('Value of String nameWithTrailingWhitespace = ' + nameWithTrailingWhitespace);

String emptyStringWithWhitespace = '     ';
System.debug('Value of String emptyStringWithWhitespace = ' + emptyStringWithWhitespace);

String escapeSequence = '\nSFDC\tStop \\ A blog about salesforce';
System.debug('Value of String escapeSequence = ' + escapeSequence);

String a = 'apple', b = 'mango';
System.debug(a<b);

String c = 'sfdc', d = 'Sfdc';
System.debug(c==d);

/*
? What is a Object data type?
* An Object data type variable can store value of any data type that is supported in apex. All data types inherit from object
* Example of Object data type:
*/

Object num = 10;
System.debug('Value of Object num = ' + num);

Object name = 'SFDC Stop';
System.debug('Value of Object name = ' + name);

Object num1 = 10, num2 = 20;
System.debug('Sum of Object num1 and num2 = ' + (num1 + num2));

Object num1 = 10, num2 = 20;
Integer num1Int = (Integer) num1, num2Int = (Integer) num2;
System.debug('Sum of Integer num1Int and num2Int = ' + (num1Int + num2Int));

/*
? What is a Blob data type?
* An Blob data type variable can store a collection of binary data as a single object. Blob is the short form for Binary Large Object.
* Example of Blob data type: Contents of an image. Blob can be converted to a String and String can be converted to a Blob
*/

Blob b1 = Blob.valueOf('test');
System.debug('Value of Blob b1 = ' + b1);

System.debug('Value of Blob b1 as string = ' + b1.toString());

YouTube Tutorials

You can check out the tutorials below as well:

Building Blocks of Apex: Variables & Data Types Explained Simply - Salesforce Apex Tutorial Part 2

Apex Gotchas! Common Variable Errors (and Writing Comments) - Salesforce Apex Tutorial Part 3

Apex Integer Data Types: Understanding Limits & Avoiding Errors - Salesforce Apex Tutorial Part 4

Unlock Precision in Apex: The Beginner Guide to Decimal Data Type - Salesforce Apex Tutorial Part 5

Apex Double, Long, Date, Datetime & Time Data Types Explained - Salesforce Apex Tutorial Part 6

Apex Id, String, Object and Blob Data Types Decoded - Salesforce Apex Tutorial Part 7

Check out the tutorials and let me know your feedback in the comments down below.

Happy Trailblazing!!