Preface – This post is part of the Object Oriented Thinking series.
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!
Amazing explanation ..! Thank you David for this wonderful post.
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.
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?
Hi David,
Please make a video tutorial on salesforce integration. Your videos are really awesome. Please keep up the good work!
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?
David =)
Where is the next post blue link!
Hahaha who knows!! =)
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?
Definitely not for free anymore
Great read. Very clever explanation.
Helped me achieve the necessary code coverage.
Thanks!!
i think u r anakin,
Awesome Tutorial, it will be really helpful for moving to salesfroce developer.
naming conventions are worst. Making complexity bcz of names.
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. =)
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.
Awesome stuff and the way you explain the things are very beautiful.
Will be waiting for your next article.
:)
Superb David ..you are like a God for Salesforce begineers. thanks a lot man for posting this awesome tutorials !!
Good articles nicely explained. Waiting for your next articles David. Thanks a lot..!!
how i can see further or next post. i want to read other chapters also
I believe this was my last tutorial!
Hi David, in the contents there are many topics after this, but cant access that. Can you please help with that?
thanks,
Ana
They haven’t been written yet =)
When can we expect new chapters?
To be honest, not sure if I’ll cover these anytime soon!
Hi David,
we are waiting for Integration
Hi David,
Any plans to finish the rest of your lectures on learning APEX here! Please let us know
Thank you,
Sinan Bunni
I definitely intend to!
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.
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.
Waiting for your next article:)
Very Useful articles.
Thanks David
David,
Next post.. :)
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.
V interested in next article too
Hey Devid,
Nice Explained but after 8 chapter all are disable…
when u upload that next chapters.??
Haven’t written them yet =) Just in planning!
Soo…
can i go for interviews ;) :P …???
If you’re up to this chapter you’re ready for interviews =)
Test
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
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.
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!
Scope of Static in apex is Limited with its current transaction.
You are absolutely correct Thomas.Good learning :)
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.
That’s very kind of you Ashish, thank you for the nice words!
I’m gonna skip Visualforce and go straight to Lightning!
Great article!
I’m pretty interested on your next article.
Thank you!
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