static keyword in Java
The static keyword
The "static" keyword in java can be used with
- a field/variable
- a method
- a block
The static variables
We cannot refer static variables using "this" keyword implicit reference in a class object. If a static variable is declared as public and final then it will behave like a global constant. The "static" variables can be accessed directly within static methods.
The static methods
A method is part of a class and it is used to implement the logic or code. A static method can be invoked without creating the instance of that class.- static methods can directly access static variables of the class and manipulate them.
- static methods can be directly accessed by ClassName.staticMethodName().
- Inside the same class, we can directly use static methods by their name.
- Inside static methods, we can’t access non-static members(instance variables or instance methods)
- static methods can’t use "this" or "super" references.
Example static methods and variable
package com.example.main; class S { static int static_var=12; //static or class variable static int showStatic_Var() //static or class method { return static_var; //static var can be accessed directly //within static methods only } } public class StaticDemo { public static void main(String[] args) {//No need To create object //of class S to access the static method or variable System.out.println("static var is "+S.static_var); System.out.println("static var is "+S.showStatic_Var()); } } Output: static var is 12 static var is 12
The static block
A segment of code enclosed within {} brackets is known as a block. We can create static blocks using static keyword in a Java program.- The code within the static block is executed automatically when the class is loaded by JVM Automatically.
- The order of execution of static blocks is the same as the order of the occurrence.
- A class can have any number of static blocks
- JVM combines them and executes it as a single block of code.
- Static methods can also be invoked within Static blocks.
"static" block example
class Test{ static { //static block 1 System.out.println("Welcome block 1"); System.out.println(add(5,17)); } static int add(int a,int b) //static method { return a+b; } } public class StaticDemo { static { //static block 2 System.out.println("Welcome block 2"); } public static void main(String[] args) { Test t=new Test(); //Nothing to do } static { static block -3 System.out.println("Welcome block 3"); } } Output: Welcome block 2 Welcome block 3 Welcome block 1 22