Java static Keyword(With Examples)

This post is about Java static keyword along with static methods, static variables, static class, and static blocks with the help of simple examples.

Java static Keyword

In Java, If we want to access class members without creating an instance of the class, we need to declare the class member with static keyword.

In Java, static keyword can be used for the following:

  • Blocks
  • Variables
  • Methods
  • Nested classes

The keyword static indicates that the particular member belongs to a class itself, rather than to an instance of that class.

  • To create a static member (block, variable, method, nested class), precede its declaration with the keyword static.
  • Static members (method, variables, nested classes) can be accessed directly from other classes using the class name.
Example
class Test {
    // static method
    static void m1() {
        System.out.println("from m1");
    }

    // non-static method
    void m2() {
        System.out.println("from m2");
    }
}

class Main {
    public static void main(String[] args) {
        Test test = new Test();
        //to call non-static method we need object
        test.m2();

        //calling static method using object
        test.m1();

        // calling static method using class name Test
        Test.m1();
    }
}
Output
from m2
from m1
from m1

Static Variables

  • If a variable is static, it gets memory only once in the class area at the time of class loading and all objects of the class access the same variable.
  • Static variables are also known as Class variables because they belongs to the class rather than the object of a class.
  • Static variables can be created at class-level only.
Example
class Employee {
    //non-static variables
    int eid;
    int salary;

    //static variable
    static String companyCeo;

    public void show() {
        System.out.println(eid + " : " + salary + " : " + companyCeo);
    }
}

public class Main {

    public static void main(String[] args) {

        Employee e1 = new Employee();

        //for non-static variable, object is compulsory
        e1.eid = 100;
        e1.salary = 5000;

        //for static variable, we do not need object
        Employee.companyCeo = "Arun";

        Employee e2 = new Employee();
        e2.eid = 101;
        e2.salary = 8000;

        e1.show();
        e2.show();
    }
}
Output
100 : 5000 : Arun
101 : 8000 : Arun
Example explained
  • Employee class contains two non-static variables eid and salary (get memory during object creation) and a static variable companyCeo (get memory when class loads).
  • The instances e1 and e2 of Employee class contains the separate copies of non-static variables and access the same static variable companyCeo with value “Arun”.

Static Blocks

  • The static block is used to initialize the static variables and is executed only once when the class is loaded in memory. 
  • A class can have multiple static blocks and each static block is executed in the same sequence in which they have been written in a program.
Example
class Employee {
int eid;
int salary;

//static variable
static String companyCeo;

//execute when class loads
//first static block
static {
companyCeo = "Arun";
System.out.println("Inside static block1");
}

//executes when you create an object
public Employee(int eid, int salary) {
this.eid = eid;
this.salary = salary;
System.out.println("Inside constructor");
}

//second static block execute after the first static block
static {
companyCeo = "Vrun";
System.out.println("Inside static block2");
}

public void show() {
System.out.println(eid + " : " + salary + " : " + companyCeo);
}
}

class Main {
public static void main(String[] args) {

Employee e1 = new Employee(100, 5000);

Employee e2 = new Employee(101, 6000);

e1.show();
e2.show();
}
}
Output
Inside static block1
Inside static block2
Inside constructor
Inside constructor
100 : 5000 : Vrun
101 : 6000 : Vrun
Example explained

As soon as the Employee class is loaded,

  • The first static block get executed and the value of static variable companyCeo set to “Arun”.
  • Then, the second static block get executed and the value of static variable companyCeo overwritten to “Vrun”.
  • Now, the constructor of e1 and e2 get executed and both will access the same static variable companyCeo with value “Vrun”.

Static Methods

  • Static methods are also known as class methods because they belongs to the class rather than the object of a class.
  • Static methods can be accessed directly in static and non-static methods but we cannot access non-static members inside static method.
Example
class Employee {
    //non-static variables
    int eid;
    int salary;

    //static variables
    static String companyCeo;
    static String companyName;

    //Employee class constructor
    public Employee(int eid, int salary) {
        this.eid = eid;
        this.salary = salary;
    }

    //non-static method
    void show() {
        System.out.print(eid + " : " + salary + " : ");
        //access static members inside non-static method
        display();
    }

    //static method
    static void display() {
        //error: cannot access non-static members inside static method
        //System.out.print(eid + " : " + salary + " : ");
        //show();
        System.out.print(companyName + " : " + companyCeo + "\n");
    }
}

class Main {

    public static void main(String[] args) {

        Employee e1 = new Employee(100, 5000);

        Employee e2 = new Employee(101, 6000);

        //to access static variables and methods, we do not need object.
        //access static variables using class 
        Employee.companyCeo = "Arun";
        Employee.companyName = "HCL";

        //access static method using class 
        Employee.display();

        e1.show();
        e2.show();
    }
}
Output
HCL : Arun
100 : 5000 : HCL : Arun
101 : 6000 : HCL : Arun
Example explained
  • Employee class contains a non-static method show() and a static method display().
  • Static method display() cannot access non-static members and show() is calling static method display().
  • Inside main() method, we are calling the non-static method show() using the class object and static members using the class name Employee.

Static Nested classes

In Java, we can declare a class inside another class (Outer class). Such classes are known as nested classes. Nested classes are of two types:

  • Static Nested Classes
  • Non-static Nested Classes (also known as Inner classes)
Differences between static and non-static nested classes:
  • Nested static class can be instantiated without instantiating its outer class (i.e. using Outer class name) but to create instance of Inner class, Outer class instance is necessary.
  • A static class can access only the static members of the outer class whereas Inner class can access both static and non-static members of the outer class.
Example
//Outer class
class OuterClass {
    private static String msg = "Hello World";

    // Static nested class
    public static class NestedStaticClass {

        // Only static members of Outer class are accessible
        
        public void show() {  // non-static method           
            System.out.println("Message from nested static class: " + msg);
        }
    }

    // Non-static nested class
    public class InnerClass {

        // Both static and non-static members
        // of Outer class are accessible 
        public void display() {  // non-static method
            System.out.println("Message from non-static nested class: " + msg);
        }
    }
}

class Main {

    public static void main(String args[]) {

        // Creating instance of nested Static class
        // using Outer class name
        OuterClass.NestedStaticClass obj = new OuterClass.NestedStaticClass();

        // Calling non-static method of nested static class
        obj.show();

        // To create instance of non-static nested class,
        // outerClass instance is necessary.
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner = outer.new InnerClass();

        // Calling non-static method of Inner class
        inner.display();

        // We can also combine above steps in one
        // step to create instance of Inner class
        //OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
    }
}
Output
Message from nested static class: Hello World
Message from non-static nested class: Hello World

Leave a Reply