Java Made Simple: What is Java static with Example?

Java static is access modifier. Access specifier specifies access. Given Example and Screenshot Simple terms. Go on read.

The "static" is one of the keywords (not reserved and prohibited) of Java. It is used as an access modifier. An access modifier modifies the access and it differs from access specifier in that access specifier specifies the access.

Let us see what static modifies the access. Everyone knows, to call an instance variable and method in Java, an object is required because Java is an OOPs language. Java maintains encapsulation through calling with object. But sometimes, it may be required to call the instance variable or method without object. Then, declare the variable or method as static. That is, a static variable or static method does not require an object to call.

Following example shows the difference between calling Java static and non-static variable.
public class Demo
  int age = 65;			           // non-static and requires an object to call
  static double salary = 9999.99;	   // static and does not require an object to call

  public static void main(String args[])
    // System.out.println(age);	           // error, it requires object as non-static
    Demo d1 = new Demo();	           // now, create an object of Demo class
    System.out.println(d1.age);    	   // it works fine because it is called with object

    System.out.println(salary);    	   // works fine even not called with object as it is static

Java static

Remove comments for age in main() and observe the error message. This is how to learn Java.

The same is the case with methods also.

Can you apply static with local variable?

Leave a Comment

Your email address will not be published.