What a Static Life?

This post was written by Salaikumar.

“Life is so static nowadays!”, says an old man combing his beard. Yes, when you get old, life would be static. because you’re no longer solving any problems.

But not for Harland Sanders, who’s more widely known as Colonel Sanders or the man behind KFC.

In programming parlance, “Static” is an interesting word. It’s a common pitfall for budding developers like us. Let’s take a look at it and see how to use it!

Static – An exciting Keyword

So, what is the Static keyword in the context of programming and what is it associated with?

You can associate Static keyword to variables (properties in object-oriented parlance), methods, blocks, and classes (Yeah, with classes as well!). What it does is to change the behavior of the associated things. Let’s review this one by one:

Static with Properties

When you associate Static with a property, the property becomes common to all instances of the class

Here’s why this matters – it is available to use readily. You can access it using the class name itself.

All the instances of the property shared the same memory space and a change to one instance updates all the other instances of the property.

Let’s take a look at the example below (I have added comments to the gist to make it self-explanatory)

package net.geekyminds.blog.statics;
/**
 * Static Examples
 * Class created to show the examples of Static keyword usage 
 */
public class StaticExamples {
    /**
     * I'm a normal property of this class
     * I will have a new memory space allocated to me for every instance
     */
    int instanceProperty;
    /**
     * I'm a static property of this class
     * I'll have only one memory space allocated to me overall. No matter how many instances of this class
     * you create, I will be common to all.
     *  ----> Yeah! - I'm just like that. I'm just common to all. <-----
     */
    static int staticProperty;
    /**
     * I'm a static method - yes, our first and favorite main method is static
     * ( Explanation later )
     * Anyone to explain me?
     * @param args
     */
    public static void main(String args[]){
        // Setting the value of static property
        // Can be directly accessed since main method is in the same class, otherwise using class name
        // ------------> Now the variable's value is 9. <------------
        staticProperty = 9;
        /**
         * Error - "Cannot resolve symbol Property"
         * You can access the normal property of a class only through it's instance
         */
         instanceProperty = 10 ;
        /**
         * Totally valid scenario
         * I create a instance of the class and accessed it's instanceProperty
         */
        StaticExamples st = new StaticExamples();
        st.instanceProperty = 10; // instanceProperty --> belongs to st object and value is 10
        // ------------> Now the variable's value is 25. <------------
        StaticExamples.staticProperty = 25 ; // staticProperty --> access using the class name
        /**
         * Yet another instance for the class
         * Now this guy will have his own memory, ie. own instanceProperty. 
         */
        StaticExamples st2 = new StaticExamples();
        st2.instanceProperty = 20; // instanceProperty -> belongs to st2 object and value is 20
    }
}

In essence, instance properties belong to an object. Static properties belong to a class

Static with Methods

Here’s an interesting scenario – what happens when you associate static to a Method?

When associated with a property, it makes the memory allocation to happen only once.

  • Do methods have memory?
  • How could block of Code have memory? It’s just kept in the sequence of instructions and invoked when called.
  • What happens in the memory stack when a method is called?

Let’s revisit the basics before we proceed so that you can visualize this. See the illustration shared below to understand the memory layout. Image courtesy: Google)

Memory-Layout-1

Now, let’s see how static is useful with methods –

When we associated Static keyword with a method, the method becomes class specific. You will be able to access it only by using the class name

Any dynamic references to it are not allowed. Do you know why?

Instance variables come to life when there’s an instance and this keyword refers to the current instance

However, Static makes the method free from any instance association

You can always call the static methods/properties in instances

Refer the class below: (Again, I’ve added comments to make the code self-explanatory. Feel free to comment if you have any questions)

package net.geekyminds.blog.statics;

/**
 * StaticExampesForMethod
 *
 * Class to explain the example uses of Static with methods
 */
public class StaticExampesForMethod {


    /**
     * Main method
     *
     * There's interesting conversation around this for you!
     * https://stackoverflow.com/questions/146576/why-is-the-java-main-method-static
     * @param args
     */
    public static void main(String[] args){
        System.out.println("I'm static!");
    }


    static int staticVariable;
    int instanceVariable;

    /**
     * instanceMethod
     *
     * just prints something out
     */
    public void instanceMethod(){
        System.out.println("I'm a instance method. You need a instance to use me");
    }

    public static void anotherStaticMethod(){
        System.out.println("Another static method");
    }

    /**
     * static method.
     *
     * this also prints something
     */
    public static void staticMethod(){
        System.out.println("I'm a static method. You can just use me right away");

        /**
         * Trying to use instance method and property
         */
        // Error - this cannot be used in static context
        this.instanceMethod();

        // Now trying to access another static method
        // No problem at this point.
        anotherStaticMethod();


        /**
         * Trying to access properties/variables
         */
        // Error - Non static variable cannot be reference from static context
        instanceVariable = 9;

        // Happy life - this variable is free from instance context.
        // Just take it and use it
        staticVariable = 30;


    }
}

Static with Classes

I wanted to keep this blog as a 10-minute read and 10-minute practice session, and it’s already touching that mark.

I’ll list the key points about using Static with a class, and later on, we can do a post dedicated to this topic:

In Java,

  • Only a Nested Class can be static
  • You can create an instance of a Nested static class. It will have all the properties of a regular Class
  • Builder Patterns –
    Why builder should be a static inner class
  • A static nested class is behaviorally a top-level class that has been nested in another top-level class, conveniently packaging it

Why do we use static nested classes in Java

Where to go from here?

Here are a couple of topics that I’d like you to read about, and try out:

  • How does Static behave when it comes to inheritance?
  • Map.Entry Class

Share your thoughts and learnings over comments. We’ll do more posts on these if required.

Hope the blog post helped you. Have a good time Coding. Bye!