Static Keyword in Java

by Trevor Page on August 9, 2012

Hello again everyone,

Before I start to talk about today’s lesson on the static keyword in Java, I’d like to give a nod to lifehacker for featuring my first five posts on the basic concepts of any programming language. The article (found here) brought a bunch of new eyes to my site and many positive comments and followers. So for that, I’m very grateful, and for you readers out there that left positive comments thank you very much, your kind words mean the world to this humble programmer!

Having said that, let’s jump right into the content. You’ve seen me use this static keyword every now and then in my coding examples, but I’ve never really explained what it meant. Perhaps you’ve been wondering what it meant, and perhaps you scoured the web for an explanation only to come up with definitions like this one:

In computer programming, a static variable is a variable that has been allocated statically — whose lifetime extends across the entire run of the program. This is in contrast to the more ephemeral automatic variables (local variables), whose storage is allocated and deallocated on the call stack; and in contrast to objects whose storage is dynamically allocated.

What!? First of all, I hate it when a definition of a term USES that same term IN the definition. So, if you don’t understand what that stuff means, no worries, I’m here to help you!

What does Static mean in Java?

The static keyword is related to a Class. Do you remember what a Class is? It’s the blueprint for an Object. Meaning when you write the code for a Class, that code is the “be all and end all” guide for how an Object lives its life in your program. In order to understand the static keyword, it’s very important that you understand the difference between a Class and an Object. So let me ramble about that difference a little bit.

An Object can be instantiated, which means that it is essentially “brought to life” in your program. An example of the instantiation of an Object could be:

Vehicle car = new Car();

Taking a page out of my last post about Inheritance, we have just instantiated a Car Object based on the Vehicle super class. So what does this imply? Well, we had to create two classes for this code, a Vehicle Class and a Car Class (a Car is a Vehicle). So somewhere in memory on the computer, a Car Object will exist. But what’s critical to note here, is that BEFORE this Car was instantiated, there was nothing in the computer’s memory, there was just two Class files (or blueprints) for a Car and a Vehicle. This is the critical difference between a Class and an Object. One exists in memory where you can access it and change it (the Object), and the other exists in part of the memory that you can’t access as a code blueprint FOR an Object (a Class).

Okay, so now that I’ve drilled that into your brains, I can talk about what the static keyword in Java means. In Java, you can make variables and methods static. Static methods and variables can also be called static methods and static variables. Why are they also called this? Because a static method (or variable) exists as part of the Class and not the instance of that Class (the Object). The implication of this is that you don’t need to instantiate an Object of that Class in order to access the static method/variable that belongs to that Class. Does that make sense to you? Perhaps not entirely, so let’s use some real examples! Static methods are often used as “helper” methods. These helper methods are nice, because you don’t have to instantiate the Object in order to use them. Let’s say there’s a global speed limit of 80, and you want to be able to check to see if you’re over the speed limit at any given moment in time, your code could look like this:

// this would be inside a Vehicle.java file
public abstract class Vehicle
{
  public static Integer speedLimit = 80;
 
  public static void checkIfOverSpeedLimit(Integer currentSpeed)
  {
    if (currentSpeed > speedLimit)
    {
      System.out.println("Slow down!  You're over the limit by " + (currentSpeed - speedLimit));
    }
    else
    {
      System.out.println("Go faster, you're only going " + currentSpeed);
    }
  }
}
 
// this would be inside a MyProgram.java file
public class MyProgram
{
  public static void main(String[] args)
  {
    Vehicle.checkIfOverSpeedLimit(70);
    Vehicle.checkIfOverSpeedLimit(155);
  }
}

So when we run this program (from the MyProgram -> main method) we’ll see the following output:


Go faster, you're only going 70
Slow down! You're over the limit by 75

So, this may not seem like we’ve done something different from any other examples I’ve given you, but there’s one main difference. We’ve called a static method on the Vehicle Class:

Vehicle.checkIfOverSpeedLimit(70);
Vehicle.checkIfOverSpeedLimit(155);

Notice how this is a little different from how we usually call methods. There’s no instantiation going on here! Normally we would have to do this:

Vehicle car = new Car();
car.checkIfOverSpeedLimit(70);

If you were to type this code into your MyProgram -> main method, you’ll see that it gets highlighted with a yellow underline and you get the following warning:

The static method checkIfOverSpeedLimit(Integer) from the type Vehicle should be accessed in a static way

Your IDE is yelling at you because you’re trying to invoke a static method (Class method) on the actual instance of the Class (the Object). Now, mind you, this will compile and it will run properly, it’s just not a recommended approach, as it’s static and should be used in the static way, which is to use the Classes name followed by the static method (or variable). i.e. Vehicle.checkIfOverSpeedLimit(Integer).

Now, there’s one little thing you’ll need to remember, and that’s the fact that you cannot use an instance variable (non-static variable) inside of a static method. This is because you’re trying to ask the blueprint (the Class) to perform some sort of operation with a variable that may not even exist yet! Remember that instance variables (non-static variables) are tied to the actual instance (or instantiated version) of their Class. So let’s say you had 6 Car objects, 3 Bus Objects and a Motorcycle Object. If you use an instance variable in the static method, how the heck is the program supposed to know what value to put into the variable? It can’t know! A good way to think of this is that when you declare a static variable on a Class, ALL the Objects that get instantiated from that Class will share that variable. If you’re familiar with programming already, this is like a global variable, as all instances of that Class will be able to access the same variable :)

Alright then, I think I’ve talked enough about what a static variable/method is. So now it’s your turn, please share your thoughts in the comments section, or continue to show your love for these tutorials by tweeting/liking/stubleupon-ing/GooglePlus-ing (top left of your screen). Also, If you want to stay informed the second one of these tutorials is posted, just sign up for my mailing list below!

Thanks everyone and best of luck!

 

Top 7 Tools to Launch Web Apps
Popular Java Tools
Free to Download
Extremely Useful

{ 14 comments… read them below or add one }

Tejus August 10, 2012 at 10:06 pm

Now it feels like we are shedding light on more and more aspects of Java :)

But I’m still confused about syntax in general in Java as against C++. I think I will have a look at some more “formal” source like a book about Java or something to figure that out…Haven’t been able to do that before for various reasons, but now your posts have compelled me to do so, so thanks for that :)

Reply

Trevor Page August 11, 2012 at 2:54 am

Syntax is the toughest part to fully comprehend once you know the basics of any programming language. At least, that’s how it is for me. With real practice, it’ll come. It took me about a month to pick up objective-c and create two iPhone apps. You’ll just need a project to work on in Java, and you’ll pick up the syntax in no time!

I’ll still be posting material once or twice a week, so keep checking back (or sign up for my email list if you haven’t already done so).

all the best,

Trevor

Reply

Stefan August 12, 2012 at 8:40 pm

If static variables/methods do not exist in memory, then where are they for your program to reference and use them? That is, how does the program grab these static variables from the blue print (class). Thanks.

Reply

Trevor Page August 12, 2012 at 9:11 pm

You make a great point Stefan, after doing some more research I see that how this is implemented may be JVM dependant but the Sun/Oracle JVM creates an Object to hold the static fields for a Class. This Object is accessible via the Unsafe Class. So there is indeed an Object in memory, it’s just not an Object that you should be using directly.

Reply

guest August 13, 2012 at 3:43 am

If static variables/methods do exist on your memory otherwise you cannot operate on them Class files (blueprints) are there on your memory, that is what class loading does. Class loading loads your compiled classes which are included in your class path to memory

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html

Reply

Rohit August 13, 2012 at 5:12 am

Beware of Static variables , they are biggest culprit of subtle issues in concurrent environment. see secrets of static in Java

Reply

Busayo August 16, 2012 at 3:44 pm

Ok…Newbie ALERT! I just started reading up on your articles. I must confess this has got me lost. From your post about variables, data structures, syntax and stuff, where do i go? I understand all this stuff about strings, Inheritance and Static keys on a logical level, but i don’t know how to begin writing any code with this and i want to start practicing soon as possible. Any help?

Reply

visoth pich August 22, 2012 at 10:37 pm

i concur with busayo like all your previous post i understood what you were talking about but i dont know how to get around to actually using them to write codes and whatnots , like right now all i can realyl do is variation of the helloworld program

Reply

Trevor Page August 23, 2012 at 6:52 am

Okay gentlemen, in my next tutorial I’ll write about files and how to read/write to them. This will give you more of an in depth and practical example of a java program!

Reply

visoth pich August 23, 2012 at 1:47 pm

cool thank you i love your tutorials

Reply

Boobalan July 16, 2013 at 12:57 pm

You just rocked it man… the example and the explanation for the keyword was awesome… well done…

Reply

ram August 1, 2013 at 2:03 am

can you post one program which use the static keyword in the inheritance program..?
thnks

Reply

Keith Hecht September 16, 2013 at 8:03 am

Thanks, A very useful information .

Reply

read here November 2, 2013 at 9:54 am

Simply desire to say your article is as astonishing. Thee clearness for your pulish is just spectacular and that i can
assume you are an expert in this subject. Welll along
with your permission let me to grasp your RSS feed to stay
updated with coming near near post. Thanks one
million and pleawse continue the gratifying work.

Reply

Leave a Comment

Powered by sweetCaptcha


Previous post:

Next post: