Satic-Keyword
Static Keyword
- The static member is associated with a class rather than an instance.
- It can be a class variable, method, or block, as well as a nested class.
Static with variable :
- A variable declared as static is known as a static variable.
- It has a common property among all other members of the class.
- It has a single copy of the value.
- It makes the program efficient in terms of memory.
Syntax:
static data_type variable_name = value ;
Example:
package quipohouse;
public class StaticVariable {
static int a = 10; // Static Variable
public int getStaticVarible() {
return StaticVariable.a; // Calling it by class name
}
public static void main(String[] args) {
StaticVariable s = new StaticVariable();
System.out.println(s.getStaticVarible());
System.out.println(StaticVariable.a);
}
}
Output:
10
10
Static with method :
- A method declared as static is known as the static method.
- It is a member of a class, rather than its object.
- It can be called by class name.
- It can be called without creating an object inside a static block.
- A static member cannot call inside the non-static block without creating its object.
Syntax:
static data_type method_name()
{
// body
}
Example:
package quipohouse;
public class StaticMethod {
public static void getStaticMethod() { // Static Method
System.out.println("Inside Static Method");
}
public static void main(String[] args) {
StaticMethod.getStaticMethod(); // Calling by its Class name
getStaticMethod(); // Calling directly
}
}
Output:
Inside Static Method
Inside Static Method
Static block :
- The static data member can be initialized if the block is marked static.
- It will be executed before the main method when the class is loaded.
- it is executed only once.
Syntax:
static {
// body
}
Example:
package quipohouse;
public class StaticVariable {
public static void getStaticVariable() {
System.out.println("Inside Static Method");
}
// Static Block
static {
System.out.println("Executed before Main Method");
}
public static void main(String[] args) {
getStaticVariable(); // static method can directly called inside static block
}
}
Output:
Executed before Main Method
Inside Static Method