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!

Introduction to the “static” keyword

January 22, 2015

Preface – This post is part of the Object Oriented Thinking series.

static [stat-ik] (adjective): lacking movement, development, or vitality.

Static is a special, often used keyword modifier in Apex that’s important enough to get its own post.

Steve Jobs described objects as “living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember.” Static is basically the opposite. Static things are lifeless and operate independently from any environment.

Static variables are variables that belong to an overall class, not a particular object of a class. Think of a static variable to be like a global variable – its value is shared across your entire org. Any particular object’s properties or values are completely irrelevant when using static.

// This example illustrates static vs. non-static variables
public class DarkJedi {
  public Integer        jedisDefeated = 0;
public static Integer totalJedisDefeated = 0;
public void executeJedi() { // Wooosh vvvzzztt! AAHHHHH! jedisDefeated = jedisDefeated + 1;
totalJedisDefeated = totalJedisDefeated + 1;
} } // Elsewhere... DarkJedi marcBenioff = new DarkJedi(); DarkJedi larryEllison = new DarkJedi(); marcBenioff.executeJedi(); larryEllison.executeJedi(); System.debug(marcBenioff.jedisDefeated); // This is 1 System.debug(larryEllison.jedisDefeated); // This is 1
// Access static variables only by class name, not object name System.debug(DarkJedi.totalJedisDefeated); // This is 2

Static methods, similarly, are methods that act globally and not in the context of a particular object of a class. Being global, static methods only have access to its provided inputs and other static (global) variables.

// This example illustrates static vs. non-static methods
public class LightJedi {
  public void slashLightsaber() {
    // Vooooom!
  }

public static String getJediCode() {
String code = 'There is no emotion, there is peace.'; code += 'There is no ignorance, there is knowledge.'; code += 'There is no passion, there is serenity.'; code += 'There is no death, there is the Force.'; return code; }
public static String describeRank(String rank) {
String description; if (rank == 'Initiate') { description = 'Jedi hopeful'; } else if (rank == 'Padawan') { description = 'Apprentice of a Jedi Knight'; } else if (rank == 'Knight') { description = 'Completed the Jedi Trials'; } else if (rank == 'Master') { description = 'David Liu'; } return description; } } // Elsewhere... LightJedi davidLiu = new LightJedi();
// Non-static methods require an object for context davidLiu.slashLightsaber();
// Static methods aren't related to a particular object LightJedi.getJediCode();
// You don't even use an object to call a static method! System.debug(LightJedi.describeRank('Master')); // David Liu

Other examples of non-static methods include lead convert, delete opportunity, and edit contact. Other examples of static methods could be convert millimeters to centimeters, subtract two numbers, and convert String to uppercase.

On the fence to use static or non-static in your particular scenario? Go non-static – objects are powerful constructs and there’s no use limiting yourself using static if in doubt. Static, as you’ll soon see however, has important and precise use cases!

Next post: Example: Using static to prevent triggers from running twice!

48 Comments
Amruta
November 3, 2020 @ 9:44 am

Amazing explanation ..! Thank you David for this wonderful post.

Reply
Thomas Reinman
May 2, 2019 @ 5:29 am

Hi David,

Thanks for this incredibly helpful post. If you’re in a situation where you have to use a static method to return a list of values that are dynamic (i.e., the size of a list contained elsewhere), how can you pass a dynamic variable into a static method, if this is even possible?

I’m asking on behalf of the Visualforce apex:charts which look pretty good. But, they are only able to reference the results of a static method, and this is only really helpful if you can have live data passing into the method. Thanks for your feedback.

Reply
Kshitij
January 30, 2019 @ 10:12 am

Hi David

I am not able to open any topics after “Introduction to the “static” keyword”.
Can you please help me out to resolve this?

Reply
Lovish Tayal
March 2, 2018 @ 6:47 am

Hi David,

Please make a video tutorial on salesforce integration. Your videos are really awesome. Please keep up the good work!

Reply
    Ben
    August 29, 2018 @ 5:22 am

    I had this same problem as well.

    I copied this code from the developer handbook into an execute anonymous window:

    public class P {
    public static boolean firstRun = true;
    }

    I got the error “static can only be used on fields of a top level type”

    Am I doing something wrong, or is there something funny about using static variables in execute anonymous?

    Reply
Angie
January 24, 2018 @ 8:41 am

David =)
Where is the next post blue link!

Reply
    David Liu
    January 24, 2018 @ 10:13 pm

    Hahaha who knows!! =)

    Reply
      Khushboo Vaidya
      September 2, 2018 @ 1:48 am

      Waiting waiting waiting for the next topics to get converted to Hyperlinks. So that, it is ‘statically’ utilize amongst all SFDC99 lovers =).

      Any plans for activating them soon?

      Reply
        Sujit Kumar Gupta
        September 6, 2019 @ 1:59 am

        Definitely not for free anymore

        Reply
Kevin Barrett
December 15, 2017 @ 2:37 am

Great read. Very clever explanation.

Helped me achieve the necessary code coverage.

Thanks!!

Reply
Anonymous
October 26, 2017 @ 6:55 am

i think u r anakin,

Reply
Amardip Budhwant
December 20, 2016 @ 11:58 pm

Awesome Tutorial, it will be really helpful for moving to salesfroce developer.

Reply
Naresh N
July 25, 2016 @ 7:21 pm

naming conventions are worst. Making complexity bcz of names.

Reply
    Angie
    January 24, 2018 @ 8:13 am

    I understand….but I am not sure if you are regular follower of sfdc99.com.

    If you go through all the chapters from the begining, you wouldn’t find these namings complex anymore. Namings are related to last chapters. =)

    Reply
Manish Verma
May 24, 2016 @ 9:04 pm

Hey David!! Very cool stuff….today I finished last available chapter and believe me I’m feeling very good about it. :)
Also your way of explaining things is very creative which binds the learner and encourages him to move to next topic…

We’re all waiting for your next post …hope it will come soon.

Reply
srinath
May 11, 2016 @ 4:12 pm

Awesome stuff and the way you explain the things are very beautiful.

Will be waiting for your next article.
:)

Reply
Sumit P
February 22, 2016 @ 1:08 pm

Superb David ..you are like a God for Salesforce begineers. thanks a lot man for posting this awesome tutorials !!

Reply
Anonymous
February 20, 2016 @ 4:14 am

Good articles nicely explained. Waiting for your next articles David. Thanks a lot..!!

Reply
Riaz khan
January 7, 2016 @ 4:23 am

how i can see further or next post. i want to read other chapters also

Reply
    David Liu
    January 13, 2016 @ 8:28 pm

    I believe this was my last tutorial!

    Reply
      Anonymous
      May 30, 2017 @ 8:56 am

      Hi David, in the contents there are many topics after this, but cant access that. Can you please help with that?
      thanks,
      Ana

      Reply
        David Liu
        May 30, 2017 @ 9:36 pm

        They haven’t been written yet =)

        Reply
          Amit
          June 12, 2017 @ 10:19 am

          When can we expect new chapters?

          Reply
            David Liu
            June 12, 2017 @ 10:14 pm

            To be honest, not sure if I’ll cover these anytime soon!

            Reply
Anonymous
November 8, 2015 @ 11:26 pm

Hi David,

we are waiting for Integration

Reply
sinanbunni
August 13, 2015 @ 7:07 am

Hi David,

Any plans to finish the rest of your lectures on learning APEX here! Please let us know

Thank you,

Sinan Bunni

Reply
    David Liu
    August 13, 2015 @ 8:11 am

    I definitely intend to!

    Reply
      Sinan Bunni
      October 3, 2015 @ 3:51 pm

      Hi David, Looking forward to continue reading your posts – really enjoying the learning curve I am gaining from them. Thank you
      Hopefully you will release them soon.

      Reply
Anonymous
July 29, 2015 @ 10:36 am

Hi David,

I guess you may be busy but really hope you update the rest of apex tutorials, especially Integrations, which seems to be the most popular interview question these days.

Reply
Anonymous
July 27, 2015 @ 8:18 am

Waiting for your next article:)

Reply
Anonymous
July 27, 2015 @ 8:18 am

Very Useful articles.

Thanks David

Reply
hp
June 23, 2015 @ 9:58 pm

David,

Next post.. :)

Reply
Prince
May 26, 2015 @ 6:17 am

when I run the block of ‘static’ code in execute anonymous, it throws an error “only top-level methods in the class are allowed to be declared as static”. I tried my code also: there also same issue.

public StringArrayTest
{

public static void generateStringArray()
{}

}

Can anyone help on this?
thank you.

Reply
HSM
April 15, 2015 @ 1:20 am

V interested in next article too

Reply
Yogesh Dighe
February 8, 2015 @ 10:10 pm

Hey Devid,

Nice Explained but after 8 chapter all are disable…
when u upload that next chapters.??

Reply
    David Liu
    February 8, 2015 @ 10:11 pm

    Haven’t written them yet =) Just in planning!

    Reply
      Yogesh Dighe
      February 8, 2015 @ 11:12 pm

      Soo…
      can i go for interviews ;) :P …???

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

        If you’re up to this chapter you’re ready for interviews =)

        Reply
        YD
        August 24, 2022 @ 3:02 am

        Test

        Reply
      Suku
      August 2, 2015 @ 5:32 am

      Hi David,
      As the light(You) are back to show light (path to coding) to many like me, please put together something in integrations.
      Thanks

      Reply
Thomas
January 27, 2015 @ 3:11 am

Just have doubt on one of the statement above “Think of a static variable to be like a global variable – its value is shared across your entire org”

According to sfdc link https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_static.htm
it says “Static variables are only static within the scope of the request. They’re not static across the server, or across the entire organization.”

I have executed your sample code above in the same org for two users under developer console on two different browsers, it doesn’t share value across entire organization.

Reply
    David Liu
    January 27, 2015 @ 8:13 am

    Great question!

    You’re 100% right that it only exists within a single execution – you’ll see a more thorough explanation of why in the next post!

    Reply
      rajkumargaikwad
      February 6, 2015 @ 5:16 am

      Scope of Static in apex is Limited with its current transaction.
      You are absolutely correct Thomas.Good learning :)

      Reply
Ashish Kumar
January 26, 2015 @ 7:28 pm

Hi David,

My name is Ashish I am 201,401 and 211 Salesforce Certified. I was looking for my career in Salesforce development but was not able to understand from where to start. I searched for many tutorials and with the God’s grace I came to know about your website http://www.sfdc99.com thanks for creating it.I started learning triggers from your website.
I would also request you to create one more tutorial on Visualforce.

Reply
    David Liu
    January 26, 2015 @ 8:17 pm

    That’s very kind of you Ashish, thank you for the nice words!

    I’m gonna skip Visualforce and go straight to Lightning!

    Reply
antonygomes
January 26, 2015 @ 5:17 am

Great article!

I’m pretty interested on your next article.

Reply
    David Liu
    January 26, 2015 @ 8:20 pm

    Thank you!

    Reply
      SriRam
      January 31, 2020 @ 4:30 am

      Hi David,
      It’s 2020 and also 1 month got over.
      Waiting for the Next Links to be activated. When can we expect from you?
      Or you have given those somewhere so that we can continue there!!!
      o_o

      Reply

Leave a Reply Cancel reply

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


*

*

Theme: Simple Style by Fimply