Sunday 7 January 2018

4.8 Static keyword in java

Static - It is a keyword in java which can be use with variables, methods and block.

STATIC VARIABLE : A static variable will share the same memory location with all the object.

Note : A static method can't use the non static variable.


class test1
{
static int i=1;
int j=1;
public int display()
{
i++;
return i;
}
public int show()
{
j++;
return j;
}
}

class staticdemo
{
public static void main(String args[])
{
test1 obj1=new test1();
System.out.println("Value of i = "+obj1.display());

test1 obj2=new test1();
System.out.println("Value of i = "+obj2.display());

test1 obj3=new test1();
System.out.println("Value of j = "+obj3.show());

test1 obj4=new test1();
System.out.println("Value of j = "+obj4.show());

}
}

STATIC METHOD : if you want to call a method without instantiating the class or you can say without creating the object of a class then we make the method static.

syntax to call a static method : classname.method();

WHY MAIN METHOD IS STATIC - Execution of the program starts with main. JVM calls the main method, but we all know that to call any method we need to create the object of that class, which is not possible for JVM, therefore main method is static.

STATIC BLOCK :  when you want to initialize the value of a static variable then you have to use static block.

static block runs before main method because it loads first when your class is loaded.
compiler will print "Hello World1" then "Hello World2" in below code.

class Test {
    static {
        System.out.println("Hello World1");
    }

    public static void main(String[] args){

        System.out.println("Hello World2");
    }
}

Can we count how many objects created for a class ??
Yes we can . hint : by using default constructor with static incremental variable.

No comments:

Post a Comment