Java static keyword tutorial
In java programming, static keyword means that the related member belongs to a class or type. If we are not going to mark the member as static, it will belong to the instance of the class or type.
-
static variables
public class Shape { static int shapeCount; protected String name; protected String color; public Shape(String name, String color) { this.name = name; this.color = color; } }
The static variable belongs to the class. So all the instances that will be created by the class will get the same value for the static variables. The static variables will consume less memory than normal variables since the static variable belongs to the class.
-
static methods
public class Shape { public static void printShape(String name, String color) { System.out.println("Color of the " + name + " is " + color); } }
Similarly, for the static variables, the static Methods belongs to the class, rather than the object of a class. Users can use the static method without initializing an object from the class.
The static method can access static members of the class only. (Cannot access non-static fields or methods in the same class).Shape.printShape("Square", "Red");
Note: normally developers use static methods in common utility classes, since no need to create an instance from that classes.
-
static blocks
The static blocks will execute before all the other methods. Even before the main method. Because of this, we can use static blocks to initialize static variables.
public class Main { private static String name; static { System.out.println("Executing static block !"); System.out.println("Vale of name: " + name); name = "John"; } public static void main(String[] args) { System.out.println("Executing main method !"); System.out.println("Vale of name: " + name); } }
Output
Executing static block ! Vale of name: null Executing main method ! Vale of name: John
<< Java super keyword Java final keyword >>