Java static Keyword:

  • static keyword indicates that a member variable or method can be accessed immediately without that class, for which it is related.
  • In simple words, this means that you can call a method, even if you have never created the object of a class, for which it is related.


purpose of Static keywords in Java:

  • Static keywords can be used to attach a variable or method to a class.
  • Variable or method that marks a static, is related to class rather than a particular instance.


static can be:

  1. class variable
  2. class method
  3. block
  4. nested class


Static Keyword can be used with:

  1. Static variables
  2. Static methods


Static variables: 

  • When a variable is declared with a static keyword, it is called class variable.
  • All examples share the same copy of the variable.
  • A class variable can be reached directly with the class, without needing to make an instance.
  • Static variables can be used to refer to the general properties of all objects (which are unique to each object) e.g. Company name of employees, college name of students.
  • At the time of class loading, the static variable class area has only one memory.


Java Static keyword Variable Declaration:




Static methods: 

  • This is a way that is related to the class and not the object instance.
  • A static method can only reach static data and change its value.
  • It can not access non-static data instance variables.
  • A static method can be directly accessed without the creation of an object.



Note:  The above add() method which is declared as static can be invoke without creating an object of class Addition in java static keyword.


Class vs Static Nested Class


static classNon-static class
static nested classes do not have access to other members of the enclosed class but it can only reach static members of the enclosed class.Non-static classes have access to other members of the external or affiliated classes, even if they have been declared private.
static nested class no need for an instance of the enclosed class to make a fixed nested class instantly.Non-static internal classes require assistance by enclosing the class to install themselves.