Keyword static

The static keyword is a special keyword in Java. It basically denotes a non-access modifier and can be applied to Java fields, methods, blocks and nested classes.

Rules for static keyword:

1) Java fields and methods declared as static are the direct members of its class.

2) Static block contains the code that is always executed whenever a class is loaded into the JVM and it can access the static members of the class only. It is executed before the constructor’s code executes.

3) Static nested classes are accessed using the enclosing class name only. They do not have access to non-static members of the enclosing class.

 

Example

See the following example for demonstrating the use of static keyword.

TestStatic.java

class Test {

int x; //instance field
static int y; //static field

//static method
static int square(int a) {
return a * a;
}

//static block
static {
System.out.println("Static block executes");
Test.y = 100; //accessing static field
}

//static nested class
static class NestedStatic {

int result = square(9); //accessing static method

void print() {
System.out.println("Result : " + result);
}
}
}

//Main class
public class TestStatic {

public static void main(String[] args) {
Test t1 = new Test(); //object 1 of class Test
Test t2 = new Test(); //object 2 of class Test
Test t3 = new Test(); //object 3 of class Test

//instance fields can have different values per object
t1.x = 10;
t2.x = 20;
t3.x = 30;

//static fields can have a single value per class
System.out.println("Value of y : " + Test.y);

//object of static nested class
Test.NestedStatic obj = new Test.NestedStatic();
obj.print(); //accessing method of static nested class
}
}

Output:

Static block executes
Value of y : 100
Result : 81