Salesforce coding lessons for the 99%
Finally, Apex tutorials for point-and-click admins! Written by a self-taught Google engineer.
  • Beginner Tutorials
    • Apex
    • Certifications
    • Career Info
    • Technical Architect
    • Visualforce
    • Videos
  • Apex Academy
  • Success Stories
  • About Me
  • Misc
    • Mailbag
    • Challenges
    • Links
    • Login to my Org
Follow @dvdkliuor SUBSCRIBE!

Variables and data types – strings, dates, numbers, booleans, and sObjects

September 28, 2013

Preface – This post is part of the Core Apex Tools series.

In this series we’ll cover the Apex fundamentals that I guarantee you’ll use in 100% of your code!

Data types are simply the different types of variables you can have. You can name your variables whatever you like as long as they’re one word. It’s an unwritten rule to have your variables in camel case.

Here’s an example of a String:

String favoriteBeer = 'Mikes Hard Lemonade';

Strings are simply text variables. You use them with all text, email, or picklist type fields in Salesforce. Notice how Strings are always wrapped in single quotes!

Here’s an example of an Integer and Decimal:

Integer numberOfBeers = 6; Decimal bloodAlcoholLevel = 0.15;

These are used in number, currency, and percentage fields in Salesforce. Integers are for number fields without any decimal places.

Booleans:

Boolean isDrunk = true;

Booleans are just either true or false. They’re used with checkboxes in Salesforce.

Dates and DateTimes:

Date courtDate = Date.today().addDays(30); DateTime timePulledOver = DateTime.now();

The difference between Dates and DateTimes is simply that the latter tracks hours, minutes, seconds, and even milliseconds! Note that we used date methods and datetime methods in the example above!

sObjects:

Contact me = [SELECT FirstName, LastName FROM Contact WHERE Email = 'dvdkliu+sfdc99@gmail.com' LIMIT 1];

Here we queried Salesforce for a record using SOQL and stored the result in an object variable… Apex is so awesome!

sObject is just a fancy name for an object in Salesforce. Custom objects will work too! We could’ve done something similar using a Prisoner__c sObject.

Next post: Data collections – lists, sets, and maps!

41 Comments
Steve
August 17, 2022 @ 12:07 pm

google

Reply
Anonymous
April 20, 2021 @ 9:22 pm

Can anyone share link of ApexAcademy videos here. Thnx in advance

Reply
Mayur
February 8, 2018 @ 10:18 pm

Hi David,

how can I access objects from Vf page and use them in coding, my requirement is I need to take 2 Usernames from VF page and change the owners of all the data from 1 user to other.( in case if any user is leaving the company and going)

can you please help me in this.

Thanks in Advance,

Reply
    David Liu
    February 8, 2018 @ 10:36 pm

    I haven’t covered Visualforce / controllers in depth, sorry!!

    Reply
      karthik
      May 16, 2020 @ 3:11 pm

      Hi David, I have been watching all of your ApexAcademy Videos and gained a lot of knowledge from you! You are so amazing, and I love the methodology you use for teaching. Thanks for your wonderful service! I just truly wish to learn LWC from you.

      Reply
        David Liu
        May 20, 2020 @ 9:30 pm

        Thanks!!

        Reply
gk questions
January 18, 2018 @ 3:20 pm

Thank you for sharing such valuable info.

Reply
Prabhu
June 6, 2017 @ 11:32 pm

Hi David,

Where to write and execute the below code? Please guide me.

Contact me = [SELECT FirstName, LastName
FROM Contact
WHERE Email = ‘dvdkliu+sfdc99@gmail.com’
LIMIT 1];

Thank you!

Reply
    David Liu
    June 7, 2017 @ 9:57 pm

    In the developer console you can execute SOQL!

    Reply
radha
July 24, 2015 @ 11:09 pm

thank u so much

Reply
sheetal kothari
July 5, 2015 @ 10:01 pm

hii liu i created button usting button and link and now i want to see this button on salesforce1 then how can i see this?

Reply
    David Liu
    July 6, 2015 @ 1:07 am

    Check out Custom Actions!

    Reply
radha
February 12, 2015 @ 9:37 am

can we do this using formula field as well?
how can we update already inserted fields using this formula?
thank u

Reply
    David Liu
    February 12, 2015 @ 6:31 pm

    Not sure what you’re referring to!

    Reply
      radha
      February 13, 2015 @ 11:05 am

      sorry , I am referring to this ex:
      Q.
      in Quotes, line item numbers are automatically selected and numbered sequentially based on all quotes in the system. Is there any way I could create a new field with formula or make a trigger to have the line item numbers be 1-10 or depending on how many products are selected? And have those numbers repeat on every quote?
      A.
      1. Create a formula field “Current Line Items” on the Quote where the formula is simply: LineItemCount
      2. Create a custom number field “Line Item Number” on Quote Line Items
      3. Create a workflow that populates the field in step 2 with the value in step 1 (you may need to add 1 to it as well)

      I have 2 questions

      1.can we do this using formula field ?

      2.how can we update batch of line items which were already inserted?
      thank u

      Reply
Jenny
October 17, 2014 @ 1:11 pm

Hi David,

I want to find out what should be the data type for multi select Pick list values, I thought they are just like the picklist values ( string) type but when I declared them in my if statement I get an error saying “condition expression must be of type Boolean”

Reply
    David Liu
    October 17, 2014 @ 7:26 pm

    They’re just like Strings – you might be looking at the wrong line of code! Checkboxes are booleans =)

    Reply
    Rajan
    February 9, 2015 @ 4:44 am

    hi david ,

    This is Rajan and I am new to salesforce .. facing problem with this code and can u plz help me

    VF page

    controller

    public class apage {
    public list arecs {
    get{
    //return [select id ,name,phone from account where billingcity = ‘hyderabad’];
    return setcon.getRecords();
    }

    }
    public apexpages.StandardSetController setcon {
    set;
    get{
    if(setcon == null){
    string str = ‘Select id,name, phone from account order by name’;
    setcon = new apexpages.StandardSetController(Database.getQueryLocator(str));
    setcon.setPageSize(10);
    }
    return setcon;

    }
    }

    public void mfirst(){

    setcon.first();
    }

    public void mnext(){
    setcon.next();
    }

    public void mprev(){

    setcon.previous();
    }

    public void mlast(){

    setcon.last();
    }
    public boolean pprev {

    set;
    get{
    return setcon.getHasPrevious();
    }
    }

    public boolean pnext {

    set;
    get{
    return setcon.getHasNext();
    }
    }
    public integer cp {
    set;
    get {
    return setcon.getPageNumber();
    }
    }

    public integer ps{set;get;}

    public void m1(){
    setcon.setPageSize(ps);
    }
    }

    Reply
      David Liu
      February 9, 2015 @ 6:58 pm

      Not gonna lie, that’s too much code for me to debug

      Reply
        Derek Xiao
        February 24, 2015 @ 9:08 am

        lol love your honesty and the tone of your replies. This is probably the wrong place to put this but I just saw your 3 videos on apex for admins with LeAnne which led me to your website.

        Thanks for taking the time out of your schedule to do this. It has been very helpful.

        – Derek

        Reply
          David Liu
          February 24, 2015 @ 8:23 pm

          Happy to help Derek =) Best of luck in your journey!

          Reply
Brad Wilcox
October 2, 2014 @ 8:08 am

How do I reference and manipulate fields in Apex with field types of Long Text Area ?

Reply
    David Liu
    October 2, 2014 @ 8:03 pm

    Regular text, picklist, and long text areas are all treated the same way =)

    Reply
Alphonse Onyeagwa
September 25, 2014 @ 12:54 pm

I forgot to add one of them should be Read Only, too.

Reply
Alphonse Onyeagwa
September 25, 2014 @ 12:52 pm

Good stuff, Mr. Liu! Real quick, I am trying to capture data already in another object, which data type should use? Some are Currency and some are texts. Please advise, and let’s catch up soon, buddy!

Reply
    David Liu
    September 25, 2014 @ 7:14 pm

    I’d keep them exactly the same! If it’s currency, def keep it as currency (in case there are multiple currencies in the org)

    Reply
saurabh
July 25, 2014 @ 11:44 am

hey David!
can you please tell me where i can write and do practice this small type of queries related to SObjects? i am new to this and not getting my way to code,so please help me to get rid of.
Thanks in advance.

Reply
    David Liu
    July 27, 2014 @ 9:40 pm

    For SOQL, use Workbench:
    https://www.sfdc99.com/2013/06/08/where-to-write-soql-queries/

    For Apex, use the Developer Console:
    https://www.sfdc99.com/2014/02/22/debug-your-code-with-system-debug/

    Reply
sai
June 9, 2014 @ 9:23 pm

Date courtDate = Date.today().addDays(30);

hey david would u mind telling me how this works

Reply
    David Liu
    June 10, 2014 @ 6:47 pm

    No problem!

    Date.today() gives today’s date
    Then we use dot notation to use the .addDays() method to Date.today()
    Using 30 as the argument for .addDays(30) adds 30 days to Date.today()

    =)

    Reply
Nitin Saxena
May 18, 2014 @ 11:07 pm

Hi David,

Does Apex support (Explicit/Implicit)Type Conversion?

Like –

String x = ‘3’;
Integer y = x (Or Are there any functions available to do so ?)

Can we get out put of y as 3 ?

Reply
    David Liu
    May 18, 2014 @ 11:46 pm

    You sure can Nitin!

    Here’s an example:
    String x = ‘3’;
    Integer y = Integer.valueOf(x);

    http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_integer.htm#apex_System_Integer_valueOf

    Reply
      Nitin Saxena
      May 19, 2014 @ 7:01 pm

      Great !! Thanks.

      Reply
Simona
April 14, 2014 @ 3:18 pm

Hi David,

in Quotes, line item numbers are automatically selected and numbered sequentially based on all quotes in the system. Is there any way I could create a new field with formula or make a trigger to have the line item numbers be 1-10 or depending on how many products are selected? And have those numbers repeat on every quote?

Thank you

By the way I am so happy I found your website. I’ve been an admin for a year and just now discovered this site. Already ordered Java book you recommended.

Reply
    David Liu
    April 14, 2014 @ 7:29 pm

    Awesome!

    So you basically want to count the number of Quote Line Items on each quote?

    Try using the LineItemCount field!
    https://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_quote.htm

    David

    Reply
      Simona
      April 15, 2014 @ 7:11 am

      David,

      Something similar but I am looking to have it in Quote Line Items (next to products). Salesforce offers Line Item Number however that is an auto number that continues, which if we give the quote to a client he has weird numbers next to his products such as 246, 247, 248. I need the numbers to be 1, 2, 3 every quote. Does that make sense?
      Thank You

      Simona

      Reply
        David Liu
        April 15, 2014 @ 7:24 pm

        Gotcha – time to think out of the box!

        So you want a field that says “1” for the first line item on a quote, “2” for the second, etc etc?

        1. Create a formula field “Current Line Items” on the Quote where the formula is simply: LineItemCount
        2. Create a custom number field “Line Item Number” on Quote Line Items
        3. Create a workflow that populates the field in step 2 with the value in step 1 (you may need to add 1 to it as well)

        All done!

        Hope this helps!
        David

        Reply
          radha
          April 10, 2015 @ 11:40 am

          I created formula field directly in step 2 and skipped step 3 and it is working
          could there be any drawbacks with my approach?
          please explain ,thanks in advance

          Reply
            radha
            April 27, 2015 @ 3:17 pm

            eagerly waiting for your reply because i found the same question ‘What are the pros and cons when using a Workflow Rule Field Update vs. a Formula Field?” in common interview questons in
            this blog and I did not find proper answer for this
            thank u

            Reply
            radha
            July 20, 2015 @ 7:42 pm

            is my question not clear ,why iam not getting reply
            I really want clarification for this doubt
            please let me know if am in the wrong track in understanding workflows and formulafields totally
            thank u

            Reply
              David Liu
              July 20, 2015 @ 7:49 pm

              If it works with a formula field, always use the formula field =)

              Less overhead, it processes immediately, etc etc.

              Reply

Leave a Reply Cancel reply

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


*

*

Theme: Simple Style by Fimply