Static Java


"static" is a keyword used as an access modifier. Novices confuse between access specifiers and access modifiers. Access specifiers are public, protected etc. and access modifiers are static, final, abstract etc. As their names indicate, access specifier specifies the access to the class by other classes and access modifier modifies the access. For example, generally to call a variable from the main(), it requires an object. If the instance variable is static, it can be called without the need of an object. One more example, a variable can be reassigned, but a final variable cannot be reassigned.

All access specifiers and modifiers cannot be applied to all at every place. For example, static access modifier can be applied to constructors, classes and local variables and can be applied to instance variables and methods. Let us see the features of a static variable or static method.

A static variable or a static method can be called in three ways.

1. Without object
2. With object
3. With class name

The above three features are used in the following Example on static Java.
public class Demo
{
  static int salary = 10_00_000;        // static variable

  public static void display()          // static method
  {
    System.out.println("Hello World");
  } 
  public static void main(String args[])
  {
    System.out.println(salary);         // calling without object

    Demo d1 = new Demo();
    System.out.println(d1.salary);      // calling with object

    System.out.println(Demo.salary);    // calling with class name

    display();                          // calling without object
    d1.display();                       //  calling with object
    Demo.display();                     // calling with class name
  }
}

Static JavaOutput Screenshot on Static Java

In the Demo class, both salary variable and display() method are declared as static. They are called in three ways as shown in the example.

More and elaborate discussion is available on static at Java static Variable Method.

Leave a Comment

Your email address will not be published.