Monday, March 20, 2023

Static in Java

Static keyword in java means 'belongs to class'. This applies to variables, methods, blocks and nested classes. 

Static variable

Static variables are loaded into the memory as soon as the JVM starts. The value of a static variable remains the same across the instances because a common static memory is allotted to it. They are accessed using Classname. The main purpose of a static variable is memory optimization when a common variable is used.

class Test{

    public static SCHOOL_NAME = "Horizon";

}

System.out.println(Test.SCHOOL_NAME);

The fields in an interface are implicitly public static final. If one object changes the value then the change gets reflected in all the objects. Static variables cannot be declared inside a method.

Static method

Static methods are also loaded when the application starts. They are mostly used as general purpose utility classes. The main() is a static method so that it can be called even before creating an object. A static method cannot be overridden.

public static void do() { }

Static block

Static block can be used to initialize static variables. Static blocks get executed when the class gets loaded into the memory. You cannot access a non-static variable from the static context in Java. If you try, it will give compile time error.

class A {

    static {

        System.out.print("hi");

    }

}

Static inner class

We can not declare top level class as static, but only inner class can be declared static.

public class Outer{

    static class Inner{

        public void my_method(){

            System.out.println("This is my nested class");

        }

    }

    public static void main(String args[]){

        Outer.Inner inner=new Outer.Inner();

        inner.my_method();

    }

}

No comments: