A Guide To The Static Keyword In Java

July 23, 2021
Best Coding Practices



Keywords are the set of reserved words in Java that are either associated with an internal process or used to represent a predefined action therefore they cannot be used as identifiers. “for”, “int” and “class” are some very basic examples of them. One such keyword is “static“. In this article, we will be discussing what are the uses of the Java static keyword, how it can be applied to classes, variables, methods and blocks, and the difference it makes.

Java Static Keyword

The Java static keyword is primarily used for memory management. The use of static in Java indicates that the particular member of the class acts as a type itself rather than as an instance of the type. It means that rather than creating multiple instances, only a single instance of that static member will be created which will be then shared among all objects of that class. Java static keyword can be used with variables, blocks methods, and nested classes.

To create a static block, variable, method, or a nested class, you need to start its declaration with the keyword “static”.

See this example of a static variable declaration:

public static int var = 0;

Static Variables

When a variable is declared static in Java, only then can we create a single copy of that variable to be used by all the objects created at the class level. Static variables are, basically, global variables and the value of this static field will be shared across all objects.

Example of Static variables

For instance, we have a class called “Student” with some basic attributes. Whenever a new object will be initialized, it will have its distinct copy of those instance variables.

Now, if we want to keep a count of the number of students or the number of objects created, it can be done by making a static count variable. As it can be accessed and updated by all instances, the count variable can be incremented upon every instance initialization.

See the Student class definition:

1. public class Student {
2.    private String name;
3.    private String ID;
4.    private String grade;
5.
6.    public static int numberOfStudents = 0;
7.   
8.    public Student(String name, String ID, String grade) {
9.        this.name = name;
10.        this.ID = ID;
11.        this. grade = grade;
12.        numberOfStudents++;
13.    }
14. }

Here, “numberOfStudents” is a static variable and it is incremented in the class constructor, now whenever an object will be initialized, numberOfStudents static variable will be incremented by one.

1. Student st1 = new Student("Sam Wilson", "st-01", "3rd");
2. Student st2 = new Student("Steve Rogers", "st-02", "7th"); 
3.
4. System.out.println("Total Students : " +Student.numberOfStudents);

Output:

Total Students: 2

Static variables are most suited to be used When the value of a variable is independent of all the objects, or the value is needed to be accessed by all the objects.

You must have noticed in this example, as static variables are independent of any object, and they can be directly accessed using their class name and do not need any object reference. Although you can access the static variables using an object reference just like a non-static variable like this, st1.numberOfStudents, it is not recommended. The reason is that it can later become difficult to identify whether it is an instance variable or a class variable. Instead of this, always refer to the static variables using their class name like done in the example above.

Static Methods

Just like static variables, Java static keyword can also be applied to methods. Methods also belong to a class, not to any object, so a static method does not require an object to be called, they can also be called directly without any object reference.

Example of static Method

Static methods are primarily used to perform any operation that does not depend on a single instance. If there is any action that is supposed to be shared with all instances of that class, then that action can be added in a static method. For example, extending the previous example, we can create a static function called “setAdmissionFee” to set the admission fee. This fee will be the same for all students regardless of their grades.

See this code snippet:

1. public static float admissionFee = 0.0;
2. public static void setAdmissionFee(float admissionFee) {
3.     Student.admissionFee = admissionFee;
4. }

There are some limitations in static methods that need to be considered like static methods can not be overridden because methods are resolved at compile time in java and method overriding is performed after that at runtime. Abstract methods can not be static and “this” or “super” keywords cannot be used in static methods.

Static Block

static block is used for initializing static variables. A static block gets executed only once when the class is first loaded. As we saw earlier, static variables can be easily initialized directly during declaration but in certain situations when you need to do the multiline processing or a static variable requires additional, multi-statement logic when initialized, a static block comes in handy. A class can also have more than one static blocks.

Static Block Example

Let’s say, if you need to initialize a list object with some initial values, this is how you can do it very easily using static blocks:

1. public class StaticBlockExample {
2.    public static List<String> subjects = new LinkedList<>();
3.
4.    static {
5.        subjects.add("Chemistry");
6.        subjects.add("Math");
7.        subjects.add("Computer Science");
8.    }
9.    static {       
10.        subjects.add("Physics");
11.        subjects.add("Sociology");
12.    }
13. }

In this scenario, it would not be possible to initialize the List object with all these pre-defined values while declaration. A static block can also be used if the initialization of some static variables requires exception handling.

Static Class

Java allows you to easily create a class within a class, basically a nested class. It helps in making your code more organized and manageable by grouping all the elements that will be used in one place. It also increases the use of encapsulation in your program.

Inner class Vs Static nested class

There are two types of nested classes. Nested classes that are not static are called inner classes whereas the nested classes that are declared as static are called static nested classes. The main difference between both of them is that the inner classes have access to all the members of the enclosed class which includes private members as well but the static nested class can only access the static members of the enclosing class, increasing the encapsulation.

In simple inner classes, without an outer class object, there cannot be an inner class object. It indicates that an object of the inner class is always strongly associated with an outer class object. On the contrary, in a static nested class, without an outer class object, a static nested class object can still exist which means that it does not have a strong association with an outer class object.

Example of static nested class

Following is a simple example of using a static nested class and accessing the variables:

1.  class OuterClass
2.  {
3.    static int static_Outer_X = 2;
4.    int outer_Y = 5;
5.    private static int private_Outer = 10;
6.
7.    // static nested class
8.    static class StaticNestedClass
9.    {
10.        void printData()
11.        {
12.            // static member of outer class can be accessed
13.            System.out.println("static member of outer class :" + static_Outer_X);
14.
15.            // private static member of outer class be accessed
16.            System.out.println("private static member of outer class: " + private_Outer);
17.        }
18.    }
19.  }
20.  public class staticClassExample
21.  {
22.    public static void main(String[] args)
23.    {
24.        // accessing a static nested class
25.        OuterClass.StaticNestedClass obj01 = new OuterClass.StaticNestedClass();
26        Obj01.printData();   
27.    }
28.  }

The above code will output:

static member of outer class : 2

private static member of outer class: 10

If you would have tried to access or print the “outer_Y” variable inside the nested class like this:

System.out.println("private non-static member of outer class: " + Outer_Y);

it would have given a compilation error as a static nested class cannot directly access non-static members.

See Also: Java Ternary Operator With Examples

Conclusion

In this article, we discussed how Java static keyword works and how it can be used with variables, methods, blocks and nested classes. Static in Java offers a list of features that you can apply to increase encapsulation in your code, make it more readable, manageable, and efficient.



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US