Static Keyword

What is Static
Static is a Non Access Modifier.

Applicable to
Static keyword can be applied on

  • Method
  • Variable
  • Class nested within another Class
  • Initialization Block

Not Applicable to
Static keyword can not be applied to

  • Class (Not Nested)
  • Constructor
  • Interfaces
  • Method Local Inner Class(Difference then nested class)
  • Inner Class methods
  • Instance Variables
  • Local Variables

Purpose of Static Keyword
Used to attach Variable / Method to class. Variable and Method marked static belong to the class rather than to any particular instance.

How to Invoke
Static variable / methods can be used without having any Instance of the class. Only class is required to invoke a static method or static variable.

Output of the above programme

Note*: Static keyword can be used with Variables & Methods. It is not applicable to class.

Static Keyword Rules
Variable / Methods marked static belong to the Class rather then to any particular Instance.
Static method/variables can be used without creating any instance of the class.
If there are instances, a static variable of a class will be shared by all instances of that class, there will be only one copy.
A static method can’t access non static variable and also it can not directly invoke non static method (But it can invoke/access method/variable via instances).