Using the Static Keyword in Java

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.

Reference to non-static member from static context

Static variables and methods are not part of an instance, There will always be a single copy of that variable no matter how many objects you create of a particular class.

For example you might want to have an immutable list of constants, it would be a good idea to keep it static and initialize it just once inside a static method. This would give you a significant performance gain if you are creating several instances of a particular class on a regular basis.

Furthermore you can also have a static block in a class as well. You can use it to assign a default value to a static variable. They are executed only once when the class is loaded into memory.

Instance variable as the name suggest are dependent on an instance of a particular object, they live to serve the whims of it. You can play around with them during a particular life cycle of an object.

Related Article: Properties Class in Java

All the fields and methods of a class used inside a static method of that class must be static or local. If you try to use instance (non-static) variables or methods, your code will not compile.

public class Week {
    static int daysOfTheWeek = 7; // static variable
    int dayOfTheWeek; // instance variable

    public static int getDaysLeftInWeek(){
        return Week.daysOfTheWeek-dayOfTheWeek; // this will cause errors
    }

    public int getDaysLeftInWeek(){
         return Week.daysOfTheWeek-dayOfTheWeek; // this is valid
    }

    public static int getDaysLeftInTheWeek(int today){
         return Week.daysOfTheWeek-today; // this is valid
    }
}

Using static to declare constants

As the static keyword is used for accessing fields and methods without an instantiated class, it can be used to declare constants for use in other classes. These variables will remain constant across every instantiation of the class. By convention, static variables are always ALL_CAPS and use underscores rather than camel case. ex:

static E STATIC_VARIABLE_NAME

As constants cannot change, static can also be used with the final modifier:
For example, to define the mathematical constant of pi:

public class MathUtilities {
     static final double PI = 3.14159265358
}

Which can be used in any class as a constant, for example:

public class MathCalculations {
     //Calculates the circumference of a circle
     public double calculateCircumference(double radius) {
         return (2 * radius * MathUtilities.PI);
     }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here