Static Method and Static Variable in Java

Static Method and Static Variable: In Java, static is keyword that can be applied to variables and methods but not to classes. static is used as an access modifier.

In Java, to call an instance variable or method, an object is required. But a static variable and method can be called without the help of an object. This is the basic difference between static and non-static in Java.

Observe the following code on Static Method and Static Variable.
public class Demo
  int marks = 50;                                     // non-static variable
  static double average = 40.6;                       // static variable

  public void display()                               // non-static method
    System.out.println("Hello 1");
  public static void show()                           // static method
    System.out.println("Hello 2");
  public static void main(String args[])
                                  // static members - no object is required
                                  // non-static members - object is required
    Demo d1 = new Demo();         // create the object

Static Method

Observe, average and show() are static members of the class Demo and are called without the need of an object. marks and display() are non-static members and are called with object d1.

Note: More indepth explanation is available at Java static Variable Method.

In and Outs on static Usage. Read when you are comfortable with the above example

  1. Can a local variable be static?

Leave a Comment

Your email address will not be published.