Static Variable, Methods and Block

Static

  • The static keyword in Java is used for memory management mainly. 
  • We can apply java static keyword with variables, methods, blocks and nested class. 
  • The static keyword belongs to the class than an instance of the class.
  • The static can be:
  • Static Variable (also known as a class variable)
Example: static String college="AMPICS";
  • Static Method (also known as a class method)
    • If you apply a static keyword with any method, it is known as a static method.
    • A static method belongs to the class rather than the object of a class.
    • A static method can be invoked without the need for creating an instance of a class.
    • A static method can access static data member and can change the value of it.
    • Example:
static void change(){
     college = "GUNI-AMPICS";
     }
  • Static Block
    • It is used to initialize the static data member.
    • It is executed before the main method at the time of classloading.
    • Example:
static{
System.out.println("static block is invoked");
}
  • Restrictions for the static method.
    • The static method can not use nonstatic data member or call the non-static method directly.
    • this and super cannot be used in static context.
  • Why is the Java main method static?
    • It is because the object is not required to call a static method.
    • If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.
Full Example:
class Counter2{
static int count=0;

Counter2()
{
count++;
System.out.println(count);
}

public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form