Explain static keyword. Also explain calling sequence of static variables, methods and blocks in java with example.

When a member (variable or method) of class declared static, it can be accessed before any
objects of its class are created, and without reference to any object.

Variables declared as static: When variables declared as static, they work like global
variables. When objects of its class are declared, no copy of a static variable is made (means
static variable is not part of object memory). All instances (objects) of the class share the
same static variable.

Methods declared as static: The most common example of static method is main method.
Main is declared as static because it must be called before any objects exist.

Methods declared as static have several restrictions :
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.
Static methods and variables can be used independently of any object. We can access them
only by specify the name of their class followed by the dot operator.
classname.method( )
classname.variableOfClass
Example :
class StaticDemo
{
static int a = 42;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("a = " + StaticDemo.a);
}
}
output:
a = 42
In calling sequence of static variables, static methods and blocks :
1. Fist static variables statements execute
2. Then static block is execute
3. Then static main method is execute
4. Then other static methods are execute.
Example:
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
meth(42);
}
}
Output :
Static block initialized.
x = 42
a = 3
b = 12
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3,
then the static block executes (printing a message), and finally, b is initialized to a * 4 or 12.
Then main( ) is called, which calls meth( ), passing 42 to x.

Comments