Salesforce Development 101: Apex Fundamentals Masterclass
Salesforce Apex Fundamentals In One Video

In this video, we are going to write our very first Apex program and you know what?It's not that hard as you imagine it would be. To write our very first program,we are going to use Developer Console.

So for that, let's click on this gear icon and from here, click on the Developer Console. A quick tip : if you want to open your Developer Console as a browser tab Then you can right click on it and click on 'Open Link in New Tab'.

But if you want to open your Developer Console in a new window, then you can directly click on it. I prefer writing in a tab, so I'll close this Pop-Up window.Let me zoom my screen a bit.Now, in your Developer Console, we are going to write some anonymous code. That means we are not going to create any Apex Trigger,we are not going to create any Apex Class,

we are going to write some quick code, just to test how Apex works. For that,click on this debug menu and choose the first option, which is 'Open Execute Anonymous Window'.

The purpose of this window is, you can write some quick code here without creating the Apex Classes orthe Apex Triggers.And, here we are going to write our very first Salesforce program, which is "Hello World".

And from here on, you should also practice writing code along with me.So, open your Developer Console in your own Salesforce Org and write what I'm writing here.Let me write a debug statement and let's write 'Hello World' in it.

To run this statement, click on this execute button here.The program ran successfully but how you can see the output?Unfortunately, Apex doesn't support an output console like many other programming languages out there.

So, to see your output, you need to open the logs. Once you execute your program, under this Logs tab,you will see a new list item. So, double click on this. These are the logs generated from our code and there are a lot of lines that you see here.

How can you see your output?For that, let's click on this 'Debug Only' option, which will only show the debug that we have put in our code.

We are simply putting a debug statement inside the program logs.And that's why we could see our output here.

This is a debug statement, which was the part of the complete program logs and that's why see our output here. So, to put a debug statement, you need to use 'System.debug' and then the string that you want to put inside the debug logs.

Let's write multiple debug statements.I have put one more debug statement, and now, if you want to execute both of these debug statements together,then you can directly click on this execute button. But let's say, I only want to execute my third line or my second debug statement,

then I can simply select it and click on "Execute Highlighted" button.For now, let's execute both our debug statements and let's also check this open log check box, which will open our debug logs directly.

You don't have to specifically open your logs.Let's click on this execute button and it's going to open our logs directly. Now let's see our debug logs, for that,let's click on this debug only check box and we see both our outputs here.

So, this was a pretty basic Apex program but this teaches you about the debug logs.And believe me, you will be writing a lot of debug statements when you'll be trying to figure out what's going wrong with your code.

Variables and Heap

Let's try to break down and understand the code that we've written in our video.
So, this was the debug statement that we have executed and as an output, we have got "Hello World" as a string in our debug logs. Now, how does Apex know that it has to print "Hello World"?


Why it did not print "System"?Why it did not print "Debug"?Why it only printed "Hello World" in the output?So, here 'system' and 'debug' are the key words that Apex already knows about, to be more precise,'system' is a class here and 'debug' is a method within that class.So, that's why Apex did not print these two statements. But why it printed "Hello World"?The key here is these quotation marks.
So, if you write anything within the single quotes, the Apex will treat that statement as a string and the system.debug method accepts a string that it can print in the output.


So, that's why we got "Hello World" in our output. Now, there could be another way to write this statement. So what we can do, we can store the string "Hello World" in a variable and then we can print the value of that variable. Variables in any programming language are meant to store some value.
Like in this example, our greeting variable is storing a string value, which is "Hello World". As soon as
you declare a variable, the Apex will know about this keyword. So, similar to the system and debug keyword, now Apex knows about the greeting keyword as well.And, whenever you are going to type in greeting or whenever you are going to use greeting, the Apex will know that you are referring to a string value called "Hello World". These variables, they store their value in the program heap size and a heap is a size of ram
that is allocated to a particular program. Sometimes you notice that your operating system doesn't respond well or it shows some lag, maybe because a problem is using high memory or maybe that program isn't responding.And one of the reason could be that program is using more heap size.


So, you need to be very cautious when you use these variables because each and every variable is going
to consume some memory. In Apex, there is a hard limit that each and every Apex program can have up to a heap size of 6 MB and in computer terms, 6 MB is a lot. So, you should get away with the heap size generally but if you have so many variables declared and maybe like, you are not using it or you are not clearing the values or nullifying your variables, then you may hit the heap size error in your Apex program.

But for now, let's focus on these variables and let's practice some variables in our Developer Console.

Primitive Data Types

Let's modify this code and let's use a variable here. So, first I'm going to remove my second debug statement and now I'm going to create a variable here. I'm going to name my variable as "greeting" and then I'm going to assign it a string value. Now, in place of this "Hello World" string here, I'm going to use my variable and let's run our code. Our output should remain the same, we should still see the "Hello World" debug statement. Let's go back to our code and let's try to break it down. So, what I've done here is, I created a variable and I stored a string value in that variable and then I printed that variable value. Whenever you create a variable, first you need to define which type of data that particular variable is going to store. In our example, we have defined that this greeting variable is going to store a string data and that's why we were able to store Hello World in the greeting variable.

Now, this part here, it's called datatype. So, string here is a datatype. Apex supports multiple types of datatypes which we are going to discuss now. But before that, let's try to change this String to maybe something else. I'm going to use one more datatype from Apex and it's called Integer, which can store a number. Now, I leave my rest of the code as it is and let's try to execute this code. So, we see an exception here and it says "Illegal assignment from String to Integer", and the reason is, on our line number one, we have a string, but we are trying to store this string value to an Integer datatype and that's not allowed.

However, if I change my "Hello World" to maybe like "123" and I execute this program, this will execute. Because now we are storing a number in our Integer datatype and the same we see in the output as well. Apart from String and Integer, Apex supports a number of datatypes and these are Boolean, String, Integer, Long, Decimal, Double, Date, Time, Datetime, Blob and ID. So, these are the primitive datatypes that are available in Apex language.

The Boolean can store a Boolean value like true or false or maybe null. So, in programming terms null means nothing. So, when you assign a null value to a variable, that means that variable doesn't store any value. It's completely null and it doesn't occupy any memory space. The string can store the string datatypes. We have already seen the example of it. We have already seen the example of Integer datatype as well, which can store a number. Long can also store a number. The difference between Integer and long is the number of digits they can store. The integer is a 32 bit datatype, so that means it can store a value from negative two billion to the positive two billion. Where Long is a 64 bit datatype, so this means it can store a value larger than what an Integer can store.

The difference between a 32 bit and a 64 bit datatype is the amount of memory they're going to occupy in your heap. So, if you use Long variable, then it means it's going to take more memory space. Now, similar to Integer or Long, we have Decimal and Double which allow us to store the numbers with decimals, so you can have some decimal digits as well. The Double is a 64 bit datatype which not only occupies more memory space, but it can also store larger values than Decimal. We also have Date which can store a date, and Time Which can store a Time. And, there's another one called Datetime, which can store a date along with the time. We also have Blob, which can store the object type of data. So, let's say if you want to store an image, then you can store that in the Blob datatype. If you want to store a file, then you can store that in Blob. So, Blob can store all type of binary data.

Now, there is a special datatype in Apex which is called ID, and this ID can store a Salesforce record I.D. or object I.D. or any kind of metadata I.D. and this I.D. can be of 15 digit or 18 digit, where 15 digit is a case sensitive I.D. and 18 digit is a non case sensitive I.D.. So, let's go back to our Developer Console and let's try to see an example of each datatype. So, here I have declared all types of variables. The first one is a String variable, and let me use that variable here. The second one is a Boolean variable, which is holding a value true. The third one is an Integer variable which is holding a number. The fourth one is a Long variable and this number is seven billion and you need to make sure that you add "L" after the number, if you want to use the Long datatype, else Apex will be confused, like whether it is an Integer or is it a Long. Then we've used a Decimal with a dot. We have also used a Double to calculate the light speed. Then we have a Date and the value assignment is not similar to what we have seen before. Here we are using a method called "newInstance" to generate a date.

This is how you declare a Date variable and assign a value to it. Then similar to Date, we also have a Time datatype to store the current time, then a Datetime datatype. Now, let's execute this code. Let's see our debug logs. So, we see our String output, we see our Boolean output. We also see our Integer, Long, Decimal and the Double output. We also see a Date, a Time and a Datetime. So, in the Datetime field, we also see the time along with the date. Now, let me go back to my code and here, let me try to remove a few of the assignments. So, I'm going to just simply declare my variables and I'll remove the assignments. And now let's execute our code again. Go to the debug logs, all we see in our output is null because we haven't assigned any value to our variables and when you don't assign a value to a variable, by default it's null because it's not occupying any memory space. So keep in mind, when you don't assign a value to a variable, it's going to be null and make sure you write these programs along with me to build your confidence in writing a program. All of these datatypes that we have seen so far, they are called primitive datatypes. There are other types of datatypes as well

String Class Methods

Here, we are going to explore some of the very useful methods from string class. So, let's find the documentation on the string class, and for that, let's search for string class in Apex on Google and you will find a reference to Salesforce developers docs. So, here, let's open this link and it will take us to the Apex developer guide, which is the official developer guide to learn Apex.

Now, here in the string class, we have quite a lot of methods and we are going to explore some of the very useful or some of the very important methods from the string class. The first method that we are going to explore is capitalize method. So, let me go to my developer console and here I'm going to create a string variable. Let's call it str, I am a string variable. So, here first, let's print this string as is, system.debug. Let's call it like actual string, and let's print the value of str.

Now, what I will do, I will simply change the I to i, and now if you want to capitalize this string, that means if you want to make the first letter in capital case, then you can use capitalize method here. So, I'm going to add a comment here, and I'll use a debug statement, and this will be a capitalized string. So, to make it capitalize, we simply need to call the capitalize method, and this will return us the capitalized string. So, let's execute this code and the second string that we will see in our debug logs should be capitalized. So, here in our first string, which is the actual string, I is in small case, but in the second string, I is in uppercase.

So, here's another important method which is contains, and you can use this method to find out if the string variable contains a particular substring. For example, we can check if our string variable, which is this one, contains the word ring. So, let's do that. Contains example, I'm going to use system debug, contains ring and we can simply use our contains method, so str dot contains and here you need to define your substring, which is ring. So in our case, the output should be true because our string definitely has the substring ring in it. So, let's execute our code. Click on debug only and the output is true. Now, let's also explore some of the other useful methods, like converting a string to upper case or lower case. So here, to convert to a string to upper case, you simply need to use a method called toUpperCase, str.toUpperCase, so this will convert your string to uppercase and to convert it to lowercase, you simply need to change the toUpperCase method to toLowerCase.

Let's execute our code and now we should see two more strings in our output. The first one is in capital case and the second one is in lower case. Let's go back to the string class and find out a few more useful methods. So, you can use a method called endsWith, just to check if your string ends with a particular substring or not. You can also use the method Equals to match your string with some other value, for example, let's try to use this equals method and this returns either true or false. So, here I will use one more debug statement, use of equals, or maybe like, is equal to ring. So, what we'll do, we'll try to match our string, which is I am a string variable to a substring called ring. So, str.Equals, and this is definitely false because our string is, I am a string variable and we are trying to match it with ring. So, this should definitely return us false. Now let's execute this one. Click on debug only and this is false. Let's also try this equals method on couple more strings. Let's create few more string variables. First one, let's call it like Manish, and second one, we are going to call again, manish, but with 'm'.

Now let's try to compare str1 with str2. So, Let me copy this and here, let's check out str1 equals to str2, and we are going to use str1 here, and instead of ring, we are going to supply str2 variable here and now let's execute our code. So, what do you think would be the output? Will it be true or false? It is false because our second string has m in small case. So, how you can avoid this, how you can ignore the case and still match your string? For that, you can convert your str1 to either lowercase or uppercase first and do the same with str2 as well, and then you can match your strings. So, what I will do, I will still use my debug statement and this time, I'm going to ignore the case. So, first I'm going to convert my str1 to lowercase. So, this is going to convert Manish to manish again with 'm' and then I'm going to match it with str2, so after toLowerCase, I'll still use my method and then str2 toLowerCase, although it's not necessary in our case because our str2 is already in lower case, or maybe like we can change the n to N, now it should be a good example and now if you will execute this code, we should see true in our output, because we are converting both the strings to lowercase and then we are matching it. So, this time, we are ignoring the case and the output is true. Let's go to the string class and find out few more useful methods. OK, so there is a method called indexOf, which you can supply a substring and this is going to return the location or the index of that substring.

For example, if you supply ring to our str variable, then it's going to return the location of this ring, which should be somewhere around 12 or 13. So, you can try it out on your own. Let me pick some other examples. There is a method called length, which returns the length of the string, so you can use this as well, there's a method called Remove which removes the particular character from your string. So, let's try this one. So, this time we are using remove method, system.debug, and we are going to remove the ring from our string, so str.remove, and we are going to remove ring. So, this will return me the string output after removing this part of the string. So, let me execute this code. So, this time, our output is, I am a st variable, so it has removed the ring substring from this particular variable.

I have a spelling mistake here. Now, let me go back to my string class and you can also use the replace method to replace one part of your string with another one, for example, this time, let's actually copy this one and we are going to replace this ring with rong. So, this would be like, I am a strong variable, so let's use our replace method and click on execute, and we have got an error and it says, method does not exist or incorrect signature. Let me go back to the, okay, so we need to define our target first and then the replacement. So, first we need to define ring here as we want to replace ring and then the value that we want to replace it with. We want to replace ring with rong, and now let's execute our code.

It should work fine and the output should be, I am a strong variable. So, it's working fine. Let's go back to string class and there are few more methods that you will be using on daily basis, like split. So, you may have to split your string by some character. For example, you may get a string with comma separated value and then if you want to break that string by comma, then you can use split variable. In our case, we are going to split our string by space. So, our string has I guess, one, two, three, four spaces, and the output of this split method is a list. So, this will be a list of string.

So, instead of a simple string variable, we are going to get a list of string variable in our output. so let me do system.debug and here split by space, and this will be like str.split, and then there's a space. Now if you will execute this code, we will get a list of string in output. So we'll get, I guess, five items one, two, three, four, five. So, now we have got an array of string, or you can also call it list of string with five items. OK, so let's go back to string class and let's have a look at few more string methods, so there is one, you can use this trim method to trim the whitespace from a string.

So, like, if your string has any whitespace at the beginning or at the end, for example, if my string has a space at the beginning and at the end, then the trim method is going to remove this extra space from this string, then you can use the value of method to convert any other data type to a string. For example, if you have an integer datatype and you want to convert it to string, then you can use value of method, and this method supports all type of data types, so it accepts integer, it also accepts a double, decimal, date or date time, it also accepts an object as well.

Apart from this, there are few more important methods like this one, isBlank and isEmpty. So, when you use isBlank, then it's going to return true or false based on if your string is empty or not. So, if your string has only whitespace, so it doesn't have any other character except whitespace, or if it's completely empty or if it's null, then the isBlank is going to return true, else it's going to return false. The isEmpty method is very similar to isBlank but it ignores the whitespace. For example, if your string has whitespace then it will return false. But if your string is empty or null then it's going to return true. Then there is isNumeric and this method simply evaluates your string and it checks if your string only contains numbers or digits, if that is the case, then it returns true, else it returns false. Then there's one more method called isWhitespace. So, if your string only has whitespace and there's no other character in your string, then this method returns True, else it returns False. So, yeah, these are some of the useful methods from string class. Try it on your own, explore as many methods as you can from this class as the string is something that you will be working with on a daily basis and you'll be using these methods quite a lot.

Escape Character

So, tell me one thing, can your string have a value like this? So, here I have a string variable called team and I'm assigning it a value, which says, my team's name is SFDCFacts Academy. So, can you have a string like this? You cannot, because this string has three single quotes and you cannot use single quotes directly in your string because the single quotes are used to either start the string or end the string. But in some cases, you would like to use single quotes in your string. So, how you can do that? For this, you need to learn about escaping characters in a string and to escape a character in a string, you can use a backslash character and when you'll use this backslash character before your single quote, you would be able to use the single quotes in your string.

So, if you would have to write the string again, we would write it like this. We would place this backslash character before all our single quotes, and this way, we will be able to use the single quotes in our string, and the single quote is not the only character that we are not allowed to use in a string. There are other characters as well. So, let's take a look at all the escape sequences in a string. So, you can use \b to use a backspace character. You can use \n to create a new line in the string. You can use \r for a carriage return, you can use \t for a tab. Or if you would like to use a backslash character in your string, then you would have to escape this one as well with a backslash character. So, in this case, you would be using two backslash characters. You could also use \o for a null character. So, you can use any of these escape sequence in your string wherever you need them. Now, let's go back to our developer console and we'll see a short example of this.

So, here in my anonymous window, I'm going to create a string variable and I'm going to assign it a value called my team's name is TKDHealthTips Academy, and if you have noticed, this is not a correct string, as developer console doesn't identify it as a correct string, and if you will try to execute your code, you will see an error, which says unexpected token str. So, you need to escape these single quotes in order to execute your code, and to do that, you can use backslash characters.

So, I'm going to use it everywhere, wherever I'm going to use a single quote, and after that, I can terminate my string with the use of one single quote. And this time we will be able to execute our code. Let me print this string in the debug log, and let's execute our code, and we will see our single quotes in our string. So, there is a single quote after team and there are single quotes before and after our team name. Now, I'll show you an example of using \n as well.

So, let's say our string says that we work on Apex and here I'm using a \n character, which prints the rest of this string in a new line. So, you use this \n to generate a new line in your string and if we will execute this again, we would see the rest of our string in a new line. Let's click on debug only and we see that we work on Apex is printed in a new line. So, you can use this backslash character to escape some of the characters which are not allowed to be used in a string directly.

String Class Methods

In this section, we are going to explore some of the very useful methods from string class. So, let's find the documentation on the string class, and for that, let's search for string class in Apex on Google and you will find a reference to Salesforce developers docs. So, here, let's open this link and it will take us to the Apex developer guide, which is the official developer guide to learn Apex. Now, here in the string class, we have quite a lot of methods and we are going to explore some of the very useful or some of the very important methods from the string class.

The first method that we are going to explore is capitalize method. So, let me go to my developer console and here I'm going to create a string variable. Let's call it str, I am a string variable. So, here first, let's print this string as is, system.debug. Let's call it like actual string, and let's print the value of str. Now, what I will do, I will simply change the I to i, and now if you want to capitalize this string, that means if you want to make the first letter in capital case, then you can use capitalize method here.

So, I'm going to add a comment here, and I'll use a debug statement, and this will be a capitalized string. So, to make it capitalize, we simply need to call the capitalize method, and this will return us the capitalized string. So, let's execute this code and the second string that we will see in our debug logs should be capitalized. So, here in our first string, which is the actual string, I is in small case, but in the second string, I is in uppercase. So, here's another important method which is contains, and you can use this method to find out if the string variable contains a particular substring. For example, we can check if our string variable, which is this one, contains the word ring. So, let's do that. Contains example, I'm going to use system debug, contains ring and we can simply use our contains method, so str dot contains and here you need to define your substring, which is ring. So in our case, the output should be true because our string definitely has the substring ring in it.

So, let's execute our code. Click on debug only and the output is true. Now, let's also explore some of the other useful methods, like converting a string to upper case or lower case. So here, to convert to a string to upper case, you simply need to use a method called toUpperCase, str.toUpperCase, so this will convert your string to uppercase and to convert it to lowercase, you simply need to change the toUpperCase method to toLowerCase. Let's execute our code and now we should see two more strings in our output. The first one is in capital case and the second one is in lower case. Let's go back to the string class and find out a few more useful methods. So, you can use a method called endsWith, just to check if your string ends with a particular substring or not.

You can also use the method Equals to match your string with some other value, for example, let's try to use this equals method and this returns either true or false. So, here I will use one more debug statement, use of equals, or maybe like, is equal to ring. So, what we'll do, we'll try to match our string, which is I am a string variable to a substring called ring. So, str.Equals, and this is definitely false because our string is, I am a string variable and we are trying to match it with ring. So, this should definitely return us false. Now let's execute this one. Click on debug only and this is false. Let's also try this equals method on couple more strings. Let's create few more string variables. First one, let's call it like Manish, and second one, we are going to call again, manish, but with 'm'.

Now let's try to compare str1 with str2. So, Let me copy this and here, let's check out str1 equals to str2, and we are going to use str1 here, and instead of ring, we are going to supply str2 variable here and now let's execute our code. So, what do you think would be the output? Will it be true or false? It is false because our second string has m in small case. So, how you can avoid this, how you can ignore the case and still match your string? For that, you can convert your str1 to either lowercase or uppercase first and do the same with str2 as well, and then you can match your strings. So, what I will do, I will still use my debug statement and this time, I'm going to ignore the case. So, first I'm going to convert my str1 to lowercase. So, this is going to convert Manish to manish again with 'm' and then I'm going to match it with str2, so after toLowerCase, I'll still use my method and then str2 toLowerCase, although it's not necessary in our case because our str2 is already in lower case, or maybe like we can change the n to N, now it should be a good example and now if you will execute this code, we should see true in our output, because we are converting both the strings to lowercase and then we are matching it. So, this time, we are ignoring the case and the output is true.

Let's go to the string class and find out few more useful methods. OK, so there is a method called indexOf, which you can supply a substring and this is going to return the location or the index of that substring. For example, if you supply ring to our str variable, then it's going to return the location of this ring, which should be somewhere around 12 or 13. So, you can try it out on your own. Let me pick some other examples. There is a method called length, which returns the length of the string, so you can use this as well, there's a method called Remove which removes the particular character from your string. So, let's try this one. So, this time we are using remove method, system.debug, and we are going to remove the ring from our string, so str.remove, and we are going to remove ring. So, this will return me the string output after removing this part of the string.

So, let me execute this code. So, this time, our output is, I am a st variable, so it has removed the ring substring from this particular variable. I have a spelling mistake here. Now, let me go back to my string class and you can also use the replace method to replace one part of your string with another one, for example, this time, let's actually copy this one and we are going to replace this ring with rong. So, this would be like, I am a strong variable, so let's use our replace method and click on execute, and we have got an error and it says, method does not exist or incorrect signature. Let me go back to the, okay, so we need to define our target first and then the replacement.

So, first we need to define ring here as we want to replace ring and then the value that we want to replace it with. We want to replace ring with rong, and now let's execute our code. It should work fine and the output should be, I am a strong variable. So, it's working fine. Let's go back to string class and there are few more methods that you will be using on daily basis, like split. So, you may have to split your string by some character. For example, you may get a string with comma separated value and then if you want to break that string by comma, then you can use split variable. In our case, we are going to split our string by space. So, our string has I guess, one, two, three, four spaces, and the output of this split method is a list. So, this will be a list of string. So, instead of a simple string variable, we are going to get a list of string variable in our output. so let me do system.debug and here split by space, and this will be like str.split, and then there's a space.

Now if you will execute this code, we will get a list of string in output. So we'll get, I guess, five items one, two, three, four, five. So, now we have got an array of string, or you can also call it list of string with five items. OK, so let's go back to string class and let's have a look at few more string methods, so there is one, you can use this trim method to trim the whitespace from a string. So, like, if your string has any whitespace at the beginning or at the end, for example, if my string has a space at the beginning and at the end, then the trim method is going to remove this extra space from this string, then you can use the value of method to convert any other data type to a string. For example, if you have an integer datatype and you want to convert it to string, then you can use value of method, and this method supports all type of data types, so it accepts integer, it also accepts a double, decimal, date or date time, it also accepts an object as well. Apart from this, there are few more important methods like this one, isBlank and isEmpty. So, when you use isBlank, then it's going to return true or false based on if your string is empty or not. So, if your string has only whitespace, so it doesn't have any other character except whitespace, or if it's completely empty or if it's null, then the isBlank is going to return true, else it's going to return false. The isEmpty method is very similar to isBlank but it ignores the whitespace. For example, if your string has whitespace then it will return false.

But if your string is empty or null then it's going to return true. Then there is isNumeric and this method simply evaluates your string and it checks if your string only contains numbers or digits, if that is the case, then it returns true, else it returns false. Then there's one more method called isWhitespace. So, if your string only has whitespace and there's no other character in your string, then this method returns True, else it returns False. So, yeah, these are some of the useful methods from string class. Try it on your own, explore as many methods as you can from this class as the string is something that you will be working with on a daily basis and you'll be using these methods quite a lot.

List Datatype - Collections in Apex

Let's have a look at this Integer variable from our video. In this variable, we are storing a student's roll number. But since a class can have multiple students, we need to declare multiple Integer variables to store the roll numbers of all those students. So, this is how we do it, right? We'll keep on declaring these variables to store all these student's roll numbers. But is it the correct way or is there any other alternative available in Apex to store this data more efficiently. Yes, there are other alternatives available in Apex which allow us to store the collection of data of same datatype. In this case, we can store all these Integer variable values in a collection.

The first collection that we are going to take a look at is "List". A list allows us to store the collection of elements of same datatype. So, if we would have to store all three roll numbers using the list, this is how we will do it. We'll create a list of Integer and we'll call it roll numbers and then this list can have all the roll numbers that we want to store. In this statement, there are a few things new for us. The first one is, these angle brackets. Why did we use these angle brackets? So, if you want to store a collection of data in list, then you need to specify what will be the datatype and you specified this data type within these angle brackets. OK. But what is this 'new'? Why do we use this new keyword? A new keyword is used to create the instance of a class and allocate memory.

So If you go back to our example, here list is a class defined in Apex language, and if you want to create a new variable from this class or if you want to create a new instance of this class, then we had to use the new keyword. We did not use the new keyword before because we were dealing with the primitive datatypes. For primitive datatypes, if you want to allocate some value, you do not need to use the new keyword. But for all the other non primitive datatypes such as List, we have to use the new keyword to first create an instance of that particular class. Now let's go back to our developer console and practice this. In my developer console, I have three Integer variables storing the roll numbers of students, and then I'm printing these variables into the debug logs. So let's first execute this code, and we see all three roll numbers printing here.

Now, let's modify this code and instead of using three different Integer variables, we are going to use 'List'. So first, we need to define the list keyword and the datatype it's going to store. I'm going to name it as roll numbers. Then remember, we need to use our 'New' keyword to first create an instance of a list class. And here we can use our curly braces to give all the values to this list. So let me copy these values one by one. And let's not forget our semicolon here. And in the debug logs, now let's try to print our list. Let's comment our previous code, or you could directly select it and click on execute highlighted as well. Let's go to our debug only mode, and here we see all three values.

The list is a dynamic datatype. So this means, you can keep on adding the items in the list. Let me close out all these debug logs first. Now, let's go back to our anonymous window and here, let's add few more items in our list. So first, we need to use our list variable and then we need to use a method called add. So, let's add few more values. Let's copy this statement two more times. And then let's print our updated list again and click on execute. So, now we should see two debug statements. The second one should have more items than the first one. You could also create an empty list by simply removing these items here and use parentheses instead of the curly braces. Now let's run this code again and our list should be empty in the beginning and then it should have three items. Let's try to understand how a list stores the data. A list stores the data based on the indices, and the first item that you insert in a list goes to index zero. If you keep on adding the items in the list, each time the index will be implemented. So, that means the list index starts from zero and it goes up to 'n' and 'n' could be any value.

So if you have hundred items, then a list can store hundred items, but if you want to store thousand items, then you can store the thousand items as well. Just keep in mind that the list index starts from zero instead of one. So if you want to access the very first item in the list, you need to get the index zero. It's possible to update an item on a particular index. So this means, if you want to update the roll number on index one, you can do that. It's also possible to remove an item from an index in the list. So let's say, if you want to remove the index 2, that's also possible.

And you can also clear all the items in the list. For each of these operations, there are separate methods in list class. And now let's try to explore most of these methods. So here I am in my developer console again. Let me just undo my changes and I'll initialize my list with three items and I'm going to print these items here. Then we have added three more items and we have printed our list again. Now, let's print one item from index one, which should be this one. So, if you want to get an item on a particular index in a list, then you need to use a method called 'get'. So let's copy our list variable and use our method called 'get'. And here you need to define the index that you want to retrieve. So, I want to retrieve this roll number which is on the second position, and since list index starts from zero, I need to give one here so that I can retrieve my second item.

And I want to print this value. So there could be two ways, either I can assign this variable value in an Integer variable, I'll call it 'rollnum', and then I can print it inside a system.debug statement. Or I could directly print that as well. I could directly copy this statement and I can directly put it within these parenthesis, both will work in the same way. Let's add a comment here, //get item on index 1. It is also possible to add an item in a list on a particular index. So let's say, I want to add a new item on index four. So currently, the item on index four is this one.

If you count the index, this is the zero index, first, second, third and fourth. Now, I want to add a new item on index four, so I can totally do that, and the item after that will be moved to the next index. So let's see a quick example of that as well. //add item on index 4. And here, I'm going to use my list variable. I am again going to use my 'add' method, which we've used before, but this time we are going to pass an index as well. So '4' will be the index, after that, I'm going to put a comma and then you can specify new value. The new value will be this one (4, 99990000). So, what it will do?

It will insert a new item, which is '99990000' on index 4, and then this item will be shifted to index 5, and this value will be shifted to index 6. The total size of list will be 7, and since we are talking about the size, let's also try to print the list size as well. Here let's print our list again. So that we can see our new item. Let's also try to see the size of the list. So for that, you can use the size method on list. //get the list size. And you can simply use your list variable and call size method. Now again, similar to the line number 22, you can put it directly inside a debug statement, and then, we are going to delete an item from a particular index. So for that, we have a method called 'remove'. // remove the item on index 3. And here again, we need to use our list variable, Then, this time we need to use a method called remove, and this remove method accepts an index.

So, let's try to remove this item, which is on index 3. And again, let's print our list so that we can see the updated items and let's print our size again as well. So this time, the size should be six, because we have removed one item from the list. In the end, let's clear our list or remove all the items from the list. For this, you can use the 'clear' method on list. So we need to use our list variable, and then, we need to call 'clear' method on this. So, this statement will clear all the items from this list and let's try to print our list and the list size again. Let's execute this code. Let's check our debug logs. So first, we have got a list of size 3, then we have added three more items and we've got six items here. Then we have accessed the item on Index-1 two times with two different methods.

First time, we have assigned the value to an Integer variable and then printed that variable. The second time, we have directly put this statement inside a debug statement. Then we have added one item on index 4. So, that's why we see this new item here. And the items after that shifted to the next index, then we have printed the list size, which was 7 because there were seven items in the list. Then we have removed one item on index 3 from the list. So this was the item, and after removing it, the new list size was 6. Then we have cleared the list, and the size became zero. These were some helpful methods that you can use on list, although there are other methods as well in the list class and you can check the complete list here on this link.

So, go to the list class and check out all the methods from the list class, and you can try playing around with all these methods. Let's also use one more method called 'set' here, because I haven't shown you the example of updating a list item. And we are going to update this item with something else. So, let's use our list variable and as we have seen, the method name is 'set', which sets a specified value on a particular index. So, we are going to use this set method, and the index will not be '2', let's make it '1', because I want to update the second item. So, that's updated on the index one, and value, we can give it like '44444444' and let's execute it again. We've got an error because we did not put a semicolon here, and let's also try to print our list after that. And one more thing, we have cleared our list before we are trying to update an item on index 1, and as you've seen from our previous examples, the by default values of all the data types is null in Apex. So this time, we may get an error, maybe like 'array index out of bounds', or it could be 'a null pointer exception' as well.

So, let's try to execute this code and let's see the output. So here, we have got an exception and it says "list index out-of-bounds", because the list does not have any item. So we cannot update an item on index 1, because there is no index 1 and there are no items on the list. But if you do that before clearing the list, this should work. Because at this time, the list has six items, and we can update the indexes from 0 to 5. And let's execute this code again. So, from our debug logs, we can see that we have updated the item on Index 1, and I hope it's clear with you that why we got that "array index out of bounds" exception, because we were trying to update something which does not exist. We were trying to update index 1, which was not there in the list.

The list did not have any item, so there were no index. So, you can not update an index if the list does not have the item. So, let's say, if our list size is six and if you try to update the index 10, you cannot do that because the list does not have index 10. So, only if an index is there on the list, then only you can update or remove the item on that particular index. Wow, lots of learning in this section . Please try to practice as many methods as you can from the list class, and do not forget to follow along with me when I write this code. This will definitely boost your confidence in writing a computer program. So, this is all in this video. In the next section, we are going to have a look at another collection variable, which is called 'set'.

Set Datatype - Collections in Apex

It was fun to learn about the list collection and we did a lot of hands on in our previous video. I am hoping that you are following along with me and practicing on your own. Now let's learn about the second collection type which is 'set', a set can also store the elements of same datatype like a list can. But, unlike list, the 'sets' are unordered. So in the list, when we were storing the items, each of the next item were being assigned to the next index. So, they were sorted by their indexes.

But in set, whenever you add a new item, you cannot directly say that this will be added on the next index, because set doesn't use index. It directly stores your data without the indexes. So, that's why we call it unordered collection of elements. The most important property of a set is, it doesn't allow duplicate data. So this means, if you try to insert the same data again in the set, it will not accept it. It will simply disregard it and it will only persist one single item of same value, although you can add as many items in set, but they all should have different values.

None of the items can we duplicate and set can accept a null value as well. Where in the list, we could add the same item as many times as we want. So the list can accept the duplicate data, but set can not. And the list is a ordered collection, where set is an unordered collection. Now, if you want to store the same roll numbers again in a set collection, this is how we would do it. So, the only change here is, instead of using list, we will use set and rest of the things remain same. The first statement here defines a set with some initial values, where the second statement initializes a set with empty values. So, it doesn't have any item in the beginning, but we can add those items later on.

Now, let's also check how set stores the data. Unlike list, set doesn't have any indexes. It simply stores your data as it is without any indexes. And if you want to get an item, it will directly get it by its value. So, in list, we used to get an item by its index, but in set, you can get an item by it's value. So, let's go back to our developer console and let's try to practice some examples on set collection. So here, let me first remove this unwanted code, because now we are aware about the collection variables. So, let's keep this example as is, and instead of list, we are going to use set here. And we are going to initialize our set with 3 roll numbers and we are going to print those roll numbers using a debug statement. Similar to list class, the set class also supports the add method, and this is how we will add the item in a set collection. Then we are going to print our roll numbers again. And from here on, instead of using the index, we are going to start using our values.

So, let's remove the rest of the code. First, let's execute this code as is, and then we'll try to do some modification. The output is very similar to what we have got in the list collection. First we have three items, then we have added three more items in the set, and after that, we have got six items. Now, let's try to run this add statement again and let's see if this adds a new item in our set or not. So keep in mind, this is a duplicate item that I'm trying to insert, so set should ignore it, and we should still see the six values in set.

So, let me comment here, // adding duplicate values, I'll simply say, "not allowed". Where is my 'n'? Let's execute this code. And even though we tried to add the item again, we still see the six items in our set, because set doesn't support the duplicate items. Now, let's try to check if a set contains that particular item or not. So for this, we are going to use the contains method. So, let's copy our set variable, and here we need to use the contains method, and this contains method returns either true or false. So, if a set has the item that we are going to give within this contains method, then it's going to return true, else it's going to return false. So, let me copy one of the value here, and give inside the contains method. And now, if you want to print the output of this statement, we can give it inside the debug statement. So, this should return true. Now let's copy the statement and give some random value. The second statement should return false because our set doesn't have this item. If you want to delete an item from a set, you can use the remove method, the same way how we use it on a list.

So, let's delete an item. The only difference here would be, instead of giving the index, you will be passing the value that you want to remove, where in the list, we have passed the index, like on which index we want to remove the item. So here, let's use our roll numbers variable and let's call the remove method, and now I'm going to remove the last value from my set. And after that, let's print our set again, so that we can see the changes. Like the list class, the set class also supports the size method to return the set size. So, let's get the set size as well. And for that, let's use our debug statement, and let's use our set variable, and let's call our size method. So, this should give us the set size. You can also check if your set is empty or not. So, let's check our set. And the method that we are going to use for that is called "is empty". So, let's copy the roll numbers variable, and let's call "is empty" method. So, like contains method, the "is empty" method also returns either true or false. So, if the set is empty, then it's going to return true, else it's going to return false. And we can also clear our set or remove all the items from the set. For that, we need to use the clear method.

The way we did in our list class. So, I'm going to copy this variable and call clear. By this time, I'm hoping you have started understanding how the programming works and how you can use variables and the debug statements in Apex. After clearing the set, let's try to check if the set is empty or not. So this time, this "is empty" statement or the "is empty" method should return true because we are removing all the items from the set just before we are calling the "is empty" method. So, I believe we have used a lot of methods. Now let's execute our code. Okay, we have got some error, and this is on line number 29, and it says - 'the method does not exist'. Let's go to our line number 29. And the reason is, we have put this clear method inside a debug statement. So, if you call a clear method, it simply clears all the values from a set but it doesn't return any value.

So unlike "is empty" method here, which returns either true or false, the clear method doesn't return any value, and if it doesn't return any value, then we can not put anything inside our debug statement. So, let me clear this from here and let's call it directly. And let's execute our code again. It's good that we are seeing these different exceptions, so you are getting clear idea about what each and every exception means. Let's go to our debug logs, and here, first we've got three items in the set, then the six items. After that, we have tried to add duplicate items, which was not possible.

Then we have checked for a correct item in the set, if it exists in the set or not, or if the set contains that item or not, so, that returned true. Then we've tried with some random value, which returned false. Then we have deleted one item from the set. And which one we deleted, let me check, (ending with ) 7765. So, after deleting the 7765, we do not have this in our set. Then we have checked the size of the set, which is five. Then we have also checked if the set is empty or not, and at that time, the set was not empty because we did not clear the set items. So, here it returned false because it was not empty. Then we cleared the items from the set, and in the end, we checked if the set is empty or not, and then it returned true.

Map Data Type - Collections in Apex

Let's learn about the last collection in Apex, and this is called Map. Similar to list and set, a map can also store the collection of data, but it stores the data in a key value pair. Let's try to understand it with the help of an example. So let's say, you teach a class and you want to store the roll numbers and the names of all your students. So, what you will do? You will write their roll numbers, and with respect to each and every roll number, you will also write the student name. The roll numbers of students can not be duplicate, as we all know it, but the names can be duplicate.

And that's what map is all about. It has keys and it has values. The keys cannot have duplicates like set, where the values can't have duplicates like list. So in this example, the roll numbers are keys, where the student names are values. To call out a student name, first you need to know their roll number and then only you can look for the student name. Right? And the same thing happens with map as well. To access a value, you need to get the value by a key.

So let's say, if you want to access the item Bill or the student Bill, then you need to access Bill through his roll number. Like set, map also doesn't use indexes. It only uses the keys and values. So, you cannot access an item by its index, you can access the item by it's keys. Let's see a map example about how you declare and initialize a map. So, here I'm declaring a map members class2020 and it's going to store the Integers and String. What? Why did we write Integer first and String later? So, the first datatype that you are going to mention in your map declaration, will be the datatype of keys and the second datatype that you're going to mention, will be the datatype of values.

So, here for class2020, we want to make the roll numbers as keys and student names as values, because student name can be duplicate and map keys need to be unique like set. So, that's why we are declaring a map of Integer and String where integers will be our keys and Strings will be our values. Now let's go back to our developer console and let's try a few examples there. So first, let's declare a map variable and initialize our map instance. This map will have Integer as keys and String as values, and let's call it as class2020.

Then we need to use our 'new' keyword to initialize the new map. So, this is a plain declaration and initialization of map. Remember, if you remove this line here, your map will be null, like all the other variables in Apex. But if you use the new keyword, your map will not be null, it will be blank. Now, in this map, first let's add a student and I'm going to put a comment here as //add a new student or item. And, to add a new item in a map, you need to use the 'put' method. In the set and list, we use the 'add' method to add a new item to our set or list, but in the map, the method name is 'put'. So, let's use our map variable and then we need to use the put method. And here, first you need to give the key. So, let's give some random roll number, and then the student name, which should be a string and to define a string in Apex, you need to use single quotes('). So, that's it. This is how you add an item in a map. Now let's print our map, so for that, let's use our debug statement and let's give our map variable inside this debug statement. And let's execute our code. Go to debug logs and here we see, there is a key in map, which is "11008890" , and this key holds a value as "Manish".

Now, let's add few more items in our map. And this time, let's change the roll number to something else, and let's print our map again. And I'm going to add one more item in my map, and this time, I'm going to use a duplicate value, but a unique key. And then, let's add one more item, where I'm going to use the duplicate key. Maybe like '94' itself and the unique value. Let's start to give it something as "Skywalker". Yeah. So, what do you think should happen? Our map should have these four items because these are the unique values and unique keys, then our map will also have the item that we have defined on line number 14. Let's actually try to put the debug statement between line number 14 and 15.

So, by line No.15, we will have five items in our map with a duplicate value as Bill, but all unique keys. But when line number 16 will execute, what it's going to do? It's going to override the value on this key, since map doesn't accept the duplicate keys. So, the value Skywalker will replace the value Bill. Let's print this again here and let's execute our code. So, we've got our four items here in our second debug statement, then in our third debug statement, we've got duplicate value, but the keys were unique, and in our last debug statement, the value Skywalker replaced the value bill.

Now, let's go back to our anonymous window and let's try a few more methods. Let me put a comment here. I'm going to call it - // update or override value. Now, let's try to access an item from the map. So I want to know, the name of the student who has the roll numbers as 11008892, for that, we have a method called "get" on the map class and let's try to see the uses of the "get" method. So, I'm going to use my map variable, then get method, and this "get" method accepts a key. So, our key or the roll number is 11008892. So, let's pass this. And this get method is going to return the value, which is "Rick", so we can directly print that in our debug statement. Let's do that. Now, let's say, Bill has unenrolled from my class, so I don't need to keep his record, right? I can remove a value from a map using the remove method, like we did in the list and the set class.

So, let's comment here, // remove an item from map. And for that, we are going to use the remove method, and this remove method also accepts the key. So, let's pass Bill's roll numbers here, and this item will be removed. Let's print our map after that. Now, let's say, you want to get all the keys from the map. For that, you can use a method called keys, and this will return a set. So, let's get all the keys. The underlying collection or data structure of map keys is set because it shares the same property like, it doesn't keep duplicate values, and it's also unordered.

So, that's why when you get all the keys, it returns a set. And to get the keys, you simply use a method called keys, and you can assign the return value of keys method to a set, and since we are using Integer as our keys, so, this will be a set of integer. And let's call it roll numbers. There is something wrong with the "N" key on my keyboard, please excuse me for that. Sometimes it doesn't work. OK. So, we have got our roll numbers and we can simply print those using our debug statement, or we could directly put this class 2020.keys inside our debug statement like this as well. Both ways are fine. It's up to you how you want to write your code.

Now, similar to keys, you can also get all the values from the map and the values are stored as a list in map. So this time, the return type will be the list. So, let's comment here, and to get the values, you simply need to use a method called values. Instead of keys, just type in values here, and it returns a list of the student names, which is a string. So, we can store it in a list variable. list of string and let's call it students. So, this is how you can store the return value of this values method inside a list. Again, you could write the class2020.values directly within the debug statement.

So, what else? Yeah. You can also check if a map has a key or not. So, like the way we did in our set class, where we checked if a set contains a value or not using the contains method. In map, we have a method called "containsKey". //Check if map has the key. And here, simply use our variable and the method name is containsKey, and here you need to pass the key that you want to check. Maybe like this one. And this is going to return either true or false. So, I'm directly going to print in my debug statement. Now, let's also try a key that we have removed. So, here on line number 25, we have removed this key from the map. So, let's try to get this key now and see what it returns. It should return false because the map doesn't have this key anymore. All right. A lot of methods, and now let's try to execute our code. Hopefully, we shouldn't get any errors.

Oh, we did get an error on line number 29 and it says it doesn't recognize the method keys. Let's see on line number 29. OK. Keys is not a method in map, It is "KeySet", which returns a set of keys of map. Now let's give it another try. And again, we have got an error and this time, it's a spelling mistake on line number 37. Because I have missed "n" here, as I said, there's something wrong with the "n" key on my keyboard. I'll have it replaced soon guys.

Please excuse me. Okay, now it got executed, and now let's try to see our output. So, here we have got all our debug logs till line number 29. Where Skywalker replaced the value Bill, then we have tried to access an item by the key 8892 and it returned the value "Rick". So, if we try to compare the output with the code, this is what we have done here on line number 22. So, we have used the get method to get the student name using the roll number. Then on line number 26, we have removed an item from the map and it should not have the value Bill. Let's see if that's the case, yeah, it doesn't have the value Bill. Then we've got all the keys of map and later we've got all the values of the map. Then we have tried to check a key, if the map contains that key or not, which returned true. And in the end, we tried with an invalid key which was deleted before, that's why this method returned false. So, a lot of learning in last three videos and you need to build solid knowledge on Apex collections because this is what you will be doing on your every day job, so, practice a lot on the collection variables.

Leave a Reply

Your email address will not be published. Required fields are marked *