Java Static

Java static is a keyword used with instance variables and methods. Generally to call instance variables (the global variables of C-lang are known as instance variables in Java) and methods, we require an object. But to call static variables and methods we do not require an object. Infact, Java static keyword is known as access modifier. An access modifier is the one which modifies the access. Here, the modification is you are allowed to call without object.

A static variable or method can be called in three ways from main() method.

1. Can be called without object
2. Can be called with an object
3. Can be called with a class name

Following example gives the usage of Java static access modifier in the above three ways.

Note: By the time you come to Java static level, I expect you know know the basic Java, writing code, compilation and execution.

public class Demo
  static int price = 100;             // static variable
  public static void display()        // static method
    System.out.println("Hello World");
  public static void main(String args[])
    Demo d1 = new Demo();
    System.out.println(price);        // call the variable without object
    System.out.println(d1.price);     // call the variable with object
    System.out.println(Demo.price);   // call the variable with class name

    display();;                       // call the method without object
    d1.display();                     // call the method with object
    Demo.display();                   // call the method with class name

Java staticOutput Screenshot on Java static

In the above code, both price variable and display() method are declared static. They are called in three different ways.

Refer for more and clear understanding of the strength of static: Java static Variable Method

Leave a Comment

Your email address will not be published.