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!

 

Free Java Roadmap

Discover exactly what you need to learn and where to start in order to become a professional coder.