Java Static Data Members or Fields, Methods and Initializer Blocks

Java Static Keyword

Java's static keyword becomes important when we want to define a class member that will be used independently at class level. When a class member is declared static it can be accessed without creating any objects of its class. Both member methods and fields (variables) can be declared static. The most common example of a static member is Java's main() method. The main() method is declared as static because it must be called before any objects exist.

Java Static Data Members or Fields

Data members or fields of a Java class declared static are called class members. There exists exactly only one copy of static fields or class members no matter how many objects of the class are finally created. A static field, also called a class variable comes into existence when the Java class is initialized. Data members declared as static are essentially global variables. When objects of its class are created they share the same copy of static field. Following example program demonstrates static data members lucidly.

/* StaticFieldDemo.java */
 
class StaticField
{
    static int objectCount = 0;
 
    public StaticField()
    {
        objectCount++;
    }
 
    public String toString()
    {
        return new String ("There are " + objectCount + " objects of class " + this.getClass().getName());
    }
 
    public static String numOfObjects()
    {
        return new String ("There are " + objectCount + " objects of class " + StaticField.class.getName());
    }
}
 
public class StaticFieldDemo
{
    public static void main(String[] args)
    {
        System.out.println(StaticField.numOfObjects());
 
        StaticField s1 = new StaticField();
        StaticField s2 = new StaticField();
        StaticField s3 = new StaticField();
 
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
}
 
OUTPUT
======
There are 0 objects of class StaticField
There are 3 objects of class StaticField
There are 3 objects of class StaticField
There are 3 objects of class StaticField

Read above program carefully, you will see a field objectCount of type int that is declared static. As it has been explained, a static field is initialized when a class is initialized. Field objectCount is initialized with 0 when class is initialized and then gets incremented by 1 each time when an object of class StaticField is created because the increment code is present inside the body of zero argument constructor of the class.

Now come to the main() method of class StaticFieldDemo and see the first statement that prints the value of objectCount and it is zero at this point. Then three objects of class StaticField are created and every time objectCount is incremented. As there is only copy of objectCount is maintained globally at the class level. So when objectCount is printed by objects s1, s2, and s3, they all print the same value.

Java Static Methods

Java static methods are used to implement class behaviors that are not affected by the state of any instances. Java static methods are also implemented to access and mutate static members of the class in case they are private and cannot be accessed publicly. Java static methods have many restrictions over themselves:

  • They can only call static methods within from them.
  • Java static methods can only access static data members or fields.
  • Java static methods cannot refer this and super

As Java static fields are called class variables, likewise, static methods are called class methods. To initialize static variables, we usually declare a static block which gets executed exactly once, when the class is first loaded.

A Java static method is always invoked without reference to a particular object. There will be a compile-time error if you try to invoke static method using the keyword this or the keyword super.

A Java static method cannot access instance variables directly. Pay attention to this statement it looks tricky. See the following code and you would understand what the first statement of this paragraph exactly says.

/* StaticMethodDemo.java */
 
class StaticMethod
{
    int instVar = 10;
    static int staticVar = 20;
 
    public static void staticMethod ()
    {
        //You can not access instVar directly.
        System.out.println(instVar); //error: Cannot make a static reference to the non-static field instVar
 
        System.out.println(staticVar);
 
        StaticMethod smObject = new StaticMethod();
        System.out.println(smObject.instVar);
    }
}
 
 
public class StaticMethodDemo
{
    public static void main(String[] args)
    {
        StaticMethod.staticMethod();
    }
}

Read the above program carefully along with in line comments and you will see that instance variable instVar cannot be accessed directly within from the method staticMethod(), and there will be a compile-time error. This piece of code will not compile until either you remove the statement System.out.println(instVar); from staticMethod() or comment it.

It is very important to note that static members cannot be accessed by this and super keywords within from a Java static method, because keyword this represents the current instance and super represents the immediate parent class's instance in inheritance. Rule of thumb is this and super never come in static method. On the contrary, within from an instance method you can access static fields by using this and super.

Another important point is Java static methods cannot be overridden during inheritance but they can be redefined. This will further be explained during inheritance.

Java Static Initializer Blocks

A Java static initializer code block is a block of code enclosed in braces '{' and '}' that runs only once when a class is initialized or loaded. Java static initializers may be used to initialize the class variables or static data members of the class and proved useful when there are local variables involved in initializing static members.

There will be a compile-time error if a return statement appears anywhere within a Java static initializer block. There will again be a compile-time error if the keyword this or the keyword super appears anywhere within a static initializer block. Static block can throw Unchecked Exceptions. It must be noted that non-static variable cannot be referenced from a static context, else there will be a compile time error. Following Java program demonstrates the static initializer block:

/* StaticInitDemo.java */
 
class One 
{
    final static int field1 = 10;
}
 
class Two
{
    final static int field2 = 10;
}
 
class Three
{
    static int field3;
 
    // static block gets executed only once 
    // when class is initialized
    static
    {
        int one = One.field1;
        int two = Two.field2;
        field3 = one + two;
    }
 
    public static void printField3()
    {
        System.out.println(field3);
    }
}
 
public class StaticInitDemo
{
    public static void main(String[] args)
    {
        Three.printField3();
    }
}
 
OUTPUT
======
20

Use of Static Members in Multi-threaded Environment

Java static members must be used with immense care and wisdom in a multi-threaded environment, because only one copy of those members is maintained at class level and all objects share the same copy when required. In this situation synchronization among accessors and mutators of static members must be there. This topic will be opened again when threads will be discussed.

Java Static Inner Classes

Java static inner classes are covered under a separate topic Java Static Inner Classes.

Last Word

In this tutorial we talked of Java's static keyword. Java static data members or static fields or class level members are synonymous terms and there is only one copy maintained of such members. Java's static methods are used to access and mutate static data members. Java static initializer blocks are used to initialize static fields. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References




Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

New seat alert app for pregnant commutersPosted on Sunday January 22, 2017

Developers launch a new app to help pregnant women get a seat on public transport while commuting.

Samsung confirms battery faults as cause of Note 7 firesPosted on Monday January 23, 2017

The firm says neither software nor hardware, other than the batteries, were at fault in Note 7.

China to crack down on censor-busting servicesPosted on Monday January 23, 2017

China is cracking down on the hi-tech ways citizens avoid official scrutiny of what they do online.

Courtesy BBC News