Static Variables and Methods in Java

Static is a Non Access Modifier in java. A static variables or methods belongs to a class rather than objects.

Static keyword in Java is used in the declaration of member methods, instance variables, inner classes and static blocks. However, static keyword is not applicable to a class. The static keyword in Java is used mainly for memory management and to share common information among all objects of a class.

Static Variable

  • Static variables are also known as class variables, they belongs to the class and not the instance if class(objects).

  • Class variables also known as Static fields are shared by all objects of a class. Regardless of how many objects we create, there is only one instance of static variable for all objects. Same copy of a static field is accessed by all objects.

  • Static variables are initialized(alocated memory) only once at the time of class loading. Static variables gets initialized before any object of that class gets created.

  • To access a static variable we don't have to create an object. We can access a static variable by using the name of the class.

  • Syntax to access static variables : <Class_Name>.<Static_Variable_Name>
Uses of Static Variables
  • We can use static variables to define class level constants. If we want all objects to share a constant value like rate of interest, value of PI(3.141), Number of students in class etc, then we declare it as a class level constant using static keyword.
  • Using static variables makes you program memory efficient as each object of class will share shame copy of static variables instead of creating it's own.
class BankAccount {
    // Static(Class) variables
    static String bankName = "CitiBank";
    static int bankAccountCount = 0;
    // Instance variables
    int id;

    BankAccount(int accountId) {
        this.id = accountId;
        bankAccountCount++;
    }
}

public class StaticVariable {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount(100);
        printDetails(account1);
        BankAccount account2 = new BankAccount(101);
        printDetails(account2);
    }

    public static void printDetails(BankAccount account){
        System.out.println("Id : " + account.id);
        System.out.println("Bank Name : " +
           BankAccount.bankName);
        System.out.println("Total Accounts : " +
           BankAccount.bankAccountCount + "\n");
    }
} 
Output
Id : 100
Bank Name : CitiBank
Total Accounts : 1

Id : 101
Bank Name : CitiBank
Total Accounts : 2

In the above program, we defined following three variables inside class BankAccount:

  • bankName : A static string variable initialized with "CitiBank", whose value is shared among all objects of BankAccount. Only one copy of this variable is created.
  • bankAccountCount : A static integer variable initialized with 0, whose value is shared among all objects of BankAccount. Only one copy of this variable is created.
  • id : A instance variable(non-static) representing account Id of bank account. A new copy of Id variable is created for every object.

We increment the value of bankAccountCount inside the constructor of BankAccount to keep track of how many object we have created till now. Inside main method of StaticVariable class, we create two objects of BankAccount, account1 and account2 and print account details.

Inside printDetails method, we use object reference to access Id(instance variable) whereas we access static variables directly using class name.

Static Methods

  • Like static variables, static methods also belongs to a class and not instances of class.

  • A static method can only access static variables and can only call other static methods of class. It cannot access non-static variables and methods.

  • A static method can be called without an object. Like static variables, we can invoke static methods using class name.

  • We cannot use "super" and "this" reference inside static method as we can invoke it without any object.
Use of Static Methods
We use static methods to write a common utility methods to be use by everyone. Static methods are heavily used in writing a shared library.
class Calculator {
    public static int addition(int a, int b) {
        return a + b;
    }
    public static int subtraction(int a, int b) {
        return a - b;
    }
}

public class StaticMethod {
    public static void main(String[] args) {
        int i = 20, j = 10;
        // Calling static methods
        int sum = Calculator.addition(i, j);
        int diff = Calculator.subtraction(i, j);
        
        System.out.println("i= " + i +",j= " + j);
        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + diff);
    }
}
Output
i= 20,j= 10
Sum: 30
Difference: 10

In the above program, we defined two static methods "addition" and "subtraction" inside Calculator class. We can access these two methods without creating any object of Calculator class. Inside main method of StaticMethod class, we are calling addition and subtraction method using class name instead of using object reference.


Static Blocks

  • Static block is a code block inside class body surrounded by { and } which gets executed once at the time of class loading. It gets executed even before main method.

  • Static blocks are used to initialize static variables.

  • Syntax of static block
    static {
    // static block statement 
    }
    
class ClassOne {
    // static variable
    static int age;
    // static block
    static {
        age = 30;
        System.out.println("Inside Static Block");
    }
}
public class StaticBlock {
    public static void main(String[] args) {
        System.out.println(ClassOne.age);
        System.out.println("Inside Main Method");
    }
}
Output
Inside Static Block
30
Inside Main Method

In the above program, we created a static code block which initializes static variable "age" with value 30. As static blocks gets executed during class loading, the print statement inside static block gets executed before the main method of StaticBlock class.


Points to remember about static keyword
  • A static variable and static method can be accessed without using creating objects.
  • static modifier cannot be applied to a class.
  • A static method can only access other static variables and methods of a class.
  • As static method cannot use super and this references.
  • Static Methods can not be overriden.