Everything you need to know about Static Keyword in Java: Explained in Detail

Everything you need to know about Static Keyword in Java: Explained in Detail

Static Variables

Let us understand the nature and role of the static keyword by looking at an example of a class and its instances. Like, the Phone class of a particular company.

public class Phone { 
    int ram; 
    string color; 
    int memory; 
    int price; 
    string model; 
    long unitSold; 

    public Phone (int ram, string color, int memory, int price, string model) { 
        this.ram = ram; 
        this.color = color; 
        this.memory = memory; 
        this.price = price; 
        this.model = model; 
        this.unitSold += 1; 
   } 
}

Please notice, the long unitSold; is a special property that will remain the same for all the phone units sold. The total number of phones sold by a company cannot be different for a particular phone model/version the same way as human population property remains the same for all humans. Every instance of this Phone class should increase the units sold by 1 digit with the help of code line this.unitSold += 1; inside the constructor.

Now, let us create some objects with this Phone class.

public class Main { 

    public static void main { 

        Phone galaxyS3 = new Phone (8, white, 45999, S3); 

        Phone galaxyS3Pro = new Phone (16, white, 65999, S3); 

        Phone galaxyS4 = new Phone (16, grey, 78999, S4); 



        System.out.println(galaxyS3.unitSold); 

        System.out.println(galaxyS3Pro.unitSold); 

        System.out.println(galaxyS4.unitSold); 
    }
}

Ideally, the result for all three print commands should be 3 in the console log because the company sold 3 smartphones in total. But that’s not the case.

        System.out.println(galaxyS3.unitSold);          //  1 

        System.out.println(galaxyS3Pro.unitSold);    //  1 

        System.out.println(galaxyS4.unitSold);          //  1

The properties that are not related to the objects and remain the same for all the class objects, we declare them as ‘static’. The static properties belong to the class rather than the instances of that class. Hence, we shouldn’t use the ‘this’ keyword for static variables in the constructor and replace it with the class name itself. So, we’ll use Phone.unitSold instead of this.unitSold

public class Phone { 

    int ram; 

    string color; 

    int memory; 

    int price; 

    string model; 

    static long unitSold; 



    public Phone (int ram, string color, int memory, int price, string model) { 

        this.ram = ram; 

        this.color = color; 

        this.memory = memory; 

        this.price = price; 

        this.model = model; 

        Human.unitSold += 1; 

     } 

}

Now the result for units sold will be 3 in the console log. Every time we create a new object, the unitSold value increases by 1.

        System.out.println(galaxyS3.unitSold);          //  3 

        System.out.println(galaxyS3Pro.unitSold);    //  3 

        System.out.println(galaxyS4.unitSold);          //  3

Static variables are not dependent on objects. Even without creating a single object, you can still access the static variable via Class.staticVariable or Phone.unitSold

Initialization of Static Variable

Initialization is the process of assigning a value to a variable. For example, int a; is declared, and we can initialize it by doing int a = 12;

Now for normal variables in a class, there are constructors to initialize the variables when new objects are created/instantiated like this.property = property;

But in the case of static variables, there are no objects. Here, the Static block comes into the picture. Static block only runs once and helps us initialize static variables inside a class.

Public class StaticBlock { 

    static int a = 4; 

    static int b;              // only declared, not initialized 


    static {                     // this is a static block 

        b = a*5;            //this will only run once when the program is loaded 

    } 


    public static void main (String[] args) { 

        StaticBlock obj = new StaticBlock (); 

        System.out.println (StaticBlock.a + “ and ” + StaticBlock.b);     // 4 and 20 

    } 

}

Static Methods

public static void main

This is the most familiar static method to anyone who has known java for a while. The question is, why this main method of the Main class is static?

This main method is the very first thing that is run by any java program. All the classes and objects have their references in the public static void main(){} function and are run through it. Without this main function, you cannot run any java program.

Let’s say you decide to remove the ‘static’ keyword and run the function as public void main(){} Java won’t be able to run this program because any function inside a class needs an object to run itself.

But it is impossible to create an object as any java program requires the main function to run first. Without it, you won’t even find the option to run the code. And if you can’t run the code, how will you create the object? And if you can’t create the object, how will you run the main function? This is the crazy paradox ‘static’ functionality helps us to break.

How? A static function doesn’t require an object to run itself. So, we can run the main function as the first function without an object by making it static.

Non-static method inside static

An example of non-static method inside a static one:

void greeting () { 

    System.out.println (“Hello world”); 

}

The above method can't be deployed inside a static method like

Public static void main { 

    void greeting () { 

    System.out.println (“Hello world”); 

    } 

} 

//OR

static void greets () { 

    greeting (); 

}

This will show an error and won’t run.

Why? Because inside any static method, you cannot run a non-static method. Anything non-static belongs to or requires an object to come into existence. And a static method does not depend on an object. Hence, you can’t have something inside static that does depend on an object.

How to deploy a non-static method inside a static method?

The problem we are facing: The non-static object greeting(); does not belong to an object.

The way to solve this problem: We can create a new object of the Main class and assign the greeting(); method to it.

static void greets () { 

    Main obj = new Main (); 

    obj.greeting(); 

}

Now the static method will accept the non-static greeting(); method as it belongs to an object now.

Static method inside non-static

An example of non-static method inside static:

static void greets () {       // this is a static function that 

    greeting (); 

} 



void greeting() {         // can be deployed inside non-static greeting() function 

    greets(); 

}

This is possible without any error because a static method does not depend on any object and is independent. Hence, it can be deployed anywhere in the program.

Conclusion

Any static variable or method belongs to the class and not to the instances of that class. Anything static is independent of objects and does not need to assign itself to an object. Hence, static variables or functions can be placed anywhere in a java program, including all non-static objects or functions.

Did you find this article valuable?

Support Kshitij Sharma by becoming a sponsor. Any amount is appreciated!