Static Member :-

What is a static member ? Static member is a member of a class that which is not interact or associate of  an instance of a class. This can be access without creating a object of a class. Moreover static members are being executed when class load in to the memory.  Further static members are accessible from any where and certain member is common for every instances. All objects use some instance of a static member.

Static Block :-

Static block is used to initialized static variables and static block is called when object loaded to memory. Moreover multiple static blocks can be declared in a class and those will be executed in order of written in the code top to bottom.

public class TestStatic {
    static int x = 0;
    static {
        x =10;
    }
    public static void main(String[] args) {
        System.out.println(x);
    }
}

Static Variables :-

Static variable can be accessble from all instances of objects or classes since stitic variables are class level variables. These variables are being allocated to memory on one time only.

Static Methods :-

Static method can be accessed via static and not static methods. And static methods can access static variables without creating objects.

Static Class :-

If a class is a static one then it should be a nested class.

public class TestStatic {
    static int x = 0;
    int y = 0;
    static {
        x =10;
    }
    public static void main(String[] args) {
        System.out.println(x);
    }
    static class TestNestedStatic{
        public static void main(String[] args) {
            //Nested class no need of instance of
            //outer class to access static variables
            x+= 10;
            System.out.println(x);
            //Nest class cannot access non static
            //variables of outer class. Below error is generating.
            System.out.println(y);
        }
    }
}

Thanks.

3 thoughts on “Java Static Blocks, Variables and Methods

Leave a Reply

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

WP Facebook Auto Publish Powered By : XYZScripts.com