Static keyword

The static modifier is used to create variables and methods that will exist independently of any instances created for the class.
All static members exist before you ever make a new instance of a class, and there will be only one copy of a static member regardless of the number of instances of that class.
In other words, all instances of a given class share the same value for any given static variable.

Here we discuss basic use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.

Class Variables or Static field

A field that’s declared with the static keyword, like this:

private static int counter;

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Person class, the instance variables are name, age, and id. Each Person object has its own values for these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables.
They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

ITCuties - Java Static Keyword

ITCuties – Java Static Keyword

How to reference Class Variable

ClassName.variableName

This makes it clear that they are class variables

You can also refer to static fields with an object reference like

p3.noOfPersonObject

Where p3 is instance of Person class.
This is discouraged because it does not make it clear that they are class variables.

Let’s see an example to understand this concept. In this class, we have created a class variable noOfPersonObject, that keep track the number of person object created. So we increment this variable in a constructor to keep track.

package com.javalatte.itcuties.statickeyword;

class Person {

    //instance variable
    private String name;
    private int age;
    private String id;

    //class variable or static variable 
    static int noOfPersonObject = 0;

    public Person() {
    }

    public Person(String name, int age, String id) {
        this.name = name;
        this.age = age;
        this.id = id;
        noOfPersonObject++;
    }

    public int getAge() {
        return age;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

}

public class ClassVariable {

    public static void main(String[] JavaLatte) {
        Person p1 = new Person("Charlie", 30, "AA001");
        System.out.println("Name : " + p1.getName() + " Age : " + p1.getAge());
        System.out.println("No of Person created : " + Person.noOfPersonObject);

        Person p2 = new Person("Katie", 28, "BB001");
        Person p3 = new Person("Kumar", 28, "CC001");
        System.out.println("No of Person created : " + Person.noOfPersonObject);
        
        //refer to static fields with an object reference
        System.out.println("Static field with object reference : " + p3.noOfPersonObject);
        
        //changing static field value
        p1.noOfPersonObject=10;
        System.out.println("Static field with object reference : " + p1.noOfPersonObject);
    }
}

Class method or static method

A method declared with the static keyword. Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.

How to reference Class Method

ClassName.methodName(args);

You can also refer to static methods with an object reference like

instanceName.methodName(args);

This is discouraged because it does not make it clear that they are class methods.

The best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.

A common use for static methods is to access static fields. For example, we could add a static method to the Person class to access the noOfPersonObject static field:

package com.javalatte.itcuties.statickeyword;

class Person1 {

    //instance variable
    private String name;
    private int age;
    private String id;

    //class variable or static variable 
    static int noOfPersonObject = 0;

    public Person1() {
    }

    public static int getNoOfPersonObject() {
        return noOfPersonObject;
    }

    public Person1(String name, int age, String id) {
        this.name = name;
        this.age = age;
        this.id = id;
        noOfPersonObject++;
    }

    public int getAge() {
        return age;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

}

public class ClassMethod {

    public static void main(String[] JavaLatte) {
        Person1 p1 = new Person1("Charlie", 30, "AA001");
        Person1 p2 = new Person1("Katie", 28, "BB001");
        Person1 p3 = new Person1("Kumar", 28, "CC001");

        // how to access static method
        System.out.println("No. of Object : " + Person1.getNoOfPersonObject());

        //discouraged ways to access static method
        System.out.println("discouraged ways to access static method : " + p1.getNoOfPersonObject());

    }
}

Static method and variable Access rules

A static method can’t access a nonstatic (instance) variable, because there is no instance!
That’s not to say there aren’t instances of the class alive on the heap, but rather that even if there are, the static method doesn’t know anything about them. The same applies to instance methods; a static method can’t directly invoke a nonstatic method

Think static = class, nonstatic = instance.
Let’s see an example to demonstrate this concept

package com.javalatte.itcuties.statickeyword;

public class StaticAccess {

    private int counter = 0;
    private static int staticCounter = 0;

    public static void main(String[] JavaLatte) {
        //Class or static methods can access class variables and class methods directly.
        staticCounter += 5;
        staticMethod();
    }

    /**
     * Instance method
     */
    public void instanceMethod() {
        System.out.println("Instance method");
        //Instance methods can access class variables and class methods directly.
        staticMethod();
        staticCounter = staticCounter + 1;
    }

    /**
     * Static method
     */
    public static void staticMethod() {
        System.out.println("staticMethod method");

        //static method can not access instance variable
        counter = counter + 1;

        //a static method can't directly invoke a nonstatic method
        instanceMethod();
    }
}
  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly – they must use an object reference

Static as Constants

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example,

static final int MAX_VALUE = 999999;
static final int MIN_VALUE = 1;
static final double PI = 3.141592653589793;

Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so because it is final.

Download this sample code here.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>