Concept of Static block ,Static Variable and Static methods

In this topic, you will learn about, The concept of Static block, Static variable, and Static methods with the help of examples.

Static block: In java, we can create a static block where static blocks execute automatically when the program executed. It is generally used for dynamic initialization of execution .static block cannot use any name or return type. Its only use static keyword. It executes automatically and we cannot re-execute for the current program scope.

Eg: static
{
System.out.print(’’hello!’’);
System.out.print(’’this is static block’’);
}

Static method: In the Java language, we can specify a static method where the static method executes only once and we cannot use the general variable or data member. By default main function is declared static type in java.so, we can’t re-execute the main function.

Eg:
Class XYZ
{
Public static void show()
{
System.out.print(’’hello!’’);
}
Public static void main(string arg[])
{
Xyz obj 1:
Obj.show; //show();
}
}

Static variable: It creates a common memory for all class objects. The static variable initializes only once but we can change the static variable value with the help of a mathematical function. It uses a static keyword for declaration.
Eg:- class XYZ

{
Static int x;
Public void change()
{
Public static void main(string arg[])
{
Xyz obj1 ,obj2,obj3;
Obj1.change();
System.out.print(obj1.x);
System.out.print(obj2.x);
System.out.print(obj3.x);
}
}

Comment below if you have queries related to the above article, The Concept of Static block, Static variable, and Static methods with the help of examples.

See also  Java Applet Program for BorderLayout