Static Variables and Methods

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.

Definition and usage: The static keyword is a non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class.

Static can be a:

  • Variable (also known as a class variable)
  • Method (also known as a class method)
  • Block
  • Nested class

If you declare any variable as static, it is known as a static variable.

  • The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
  • The static variable gets memory only once in the class area at the time of class loading.
  • Advantages of static variable
  • It makes your program memory efficient by saving memory.

A static method can be accessed without creating an object of the class first:

public class Main {
  // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  public void myPublicMethod() {
    System.out.println("Public methods must be called by creating objects");
  }

  // Main method
  public static void main(String[ ] args) {
    myStaticMethod(); // Call the static method
    // myPublicMethod(); This would output an error

    Main myObj = new Main(); // Create an object of Main
    myObj.myPublicMethod(); // Call the public method
  }
}

Check out these resources: