Use of static Keyword in Java

The static keyword belongs to the class rather than instance of the class. We can simply say that the members belongs to the class itself. As a result, you can access the static member without creating the instance for the class. The static keyword can be applied to variables, methods, blocks and nested class. Lets see them one by one.

Java static variable

If we declare a variable with “static” keyword, then it is called as static variable. For example

static int y=0;

All the instance of the class share the same copy of the variable, a static variable can be accessed directly by calling “<<ClassName>>.<<VariableName>>” without need to create instance for the class.

For a better understading we will see an example without and with static variable.

Without Static Variable

public class StudentExample 
{
    String studentName;
    int age;
    
    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void disp()
    {
        System.out.println("Stundent Name : "+studentName+" Age : "+age);
    }
   
    public static void main(String args[])
    {
        StudentExample s1 = new StudentExample();
        s1.setStudentName("JavaInterviewPoint");
        s1.setAge(22);
        
        StudentExample s2 = new StudentExample();
        
        s1.disp();
        s2.disp();
    }
}

When we run the above code we will get the below output

Stundent Name : JavaInterviewPoint Age : 22
Stundent Name : null Age : 0

We have set values only with instance s1 and not with s2 so we are getting null and 0. Since the Non-static variable (Instance) variable are associated with each instance we are getting different values.

Lets make those variable static now

With Static Variable

public class StudentExample 
{
    static String studentName;
    static int age;
    
    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void disp()
    {
        System.out.println("Stundent Name : "+studentName+" Age : "+age);
    }
   
    public static void main(String args[])
    {
        StudentExample s1 = new StudentExample();
        s1.setStudentName("JavaInterviewPoint");
        s1.setAge(22);
        
        StudentExample s2 = new StudentExample();
        
        s1.disp();
        s2.disp();
    }
}

When we run the above code we will get the below output

Stundent Name : JavaInterviewPoint Age : 22
Stundent Name : JavaInterviewPoint Age : 22

Since we have changed variable into static, All instances share the same copy of the variable and hence we are getting the same values even though we have not set values using s2 instance.

Java static method

If we declare a method with “static” keyword, then the method is called as static method.

  • The static method belongs to class rather than object.
  • A static method can access static varaibles directly and it cannot access non-static variables.
  • A static method can only call a static method directly and it cannot call a non-static method from it.
  • super and this keyword cannot be used in a static method.
  • A static method can be directly called by using the class name <<ClassName>>.<<MethodName>> rather than objectThis is the main reason we have declared our main() method as static. If not the JVM has to create object first and call the main() method which causes the problem of having extra memory allocation.

In the below example we can see that we are calling the displayStudentDetails() method directly with the classname and not with instance.

public class StudentExample 
{
    static String studentName;
    static int age;
    
    public static void displayStudentDetails()
    {
        StudentExample.studentName ="JavaInterviewPoint";
        StudentExample.age = 22;
        /*studentName ="JavaInterviewPoint";
        age = 22;*/
        System.out.println("Stundent Name : "+studentName+" Age : "+age);
    }
   
    public static void main(String args[])
    {
        StudentExample.displayStudentDetails();
    }
}

Java static block

The static block, is a block of code inside a Java class that will be executed when a class is first loaded in to the JVM. Mostly the static block will be used for initializing the variables.

Lets take a look into the below code.

public class Test 
{
    static int i;
    static 
    {
        System.out.println("Inside static block");
        i=10;
    }
    public static void main(String args[])
    {
        System.out.println(i);
    }
}

In the above code we can see that we are initializing the variable “i” to 10. This happens when the class is loaded by the JVM even before calling the main() method.

Can a static block exist without a main() method ?

The answer is Yes. You can have static block alone in the class without a main method. We all know dynamic loading of a class using Class.forName which we mostly use while loading our JDBC drivers. When we look into the Driver class it will have only the static block and nothing else.

Lets take a look into the Driver class of MySql.

public class Driver extends NonRegisteringDriver implements java.sql.Driver 
{
    static 
    {
        try 
        {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) 
        {
            throw new RuntimeException("Can't register driver!");
        }
    }
    public Driver() throws SQLException 
    {
        // Required for Class.forName().newInstance()
    }
}

As we all know that static block gets executed while loading of the class, so when the Driver class is loaded it actually passes its object to the registerDriver() method of DriverManager class.

Java static class

In Java only nested classes are allowed to be declared as static, if we declare a top level class as static then it will throw error. Even though static classes are nested inside a class, they doesn’t need the reference of the outer class they act like outer class only whereas on the other hand non-static nested class need reference of the outer class.

public class Users 
{
    static class VipUsers
    {
        public void displayVipUsers()
        {
            System.out.println("Welcome Vip User");
        }
    }
    class NormalUsers
    {
        public void displayNormalUsers()
        {
            System.out.println("Welcome Normal User");
        }
    }
    
    public static void main(String args[])
    {
        //Nested static class doesn't require instantiation of the outer class
        Users.VipUsers vip = new Users.VipUsers();
        vip.displayVipUsers();
        
        /*Below line will throw error as the non-static class require 
        instantiaion of the outer class
        Users.NormalUsers normal = new Users.NormalUsers();*/
        
        //Nested non-static class require instantiation of the outer class
        Users users = new Users();
        Users.NormalUsers normal = users.new NormalUsers();
        normal.displayNormalUsers();
    }
}

In our Users class we have two nested VipUser which is a static class and NormalUser which is a non-static class.

  • Nested static class doesn’t require the outer class to be instantiated and hence we can create instance for the inner static class directly. Like below
     Users.VipUsers vip = new Users.VipUsers();
  • Nested non-static class requires the outer class to be instantiated first, and inner class object is created on top of it.
    Users users = new Users();
    Users.NormalUsers normal = users.new NormalUsers();
  • When we try to a Non-static method just like a static method
 Users.NormalUsers normal = new Users.NormalUsers();

We will get this error. Must qualify the allocation with an enclosing instance of type Users (e.g. x.new A() where x is an instance of Users).

Leave a Reply

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