Java Static Variables and Methods

Static is a Non Access Modifier in java. It is mainly used to attach a Variable or Method to a Class. A static variables or methods belongs to a class rather than objects.

Static keyword in Java is used in the declaration of member methods, instance variables, inner classes and static blocks. However, static keyword is not applicable to a class.

Static Variable

  • Static variables are also known as class variables as they belongs to the class and not the instance if class(objects).

  • Class variables also known as Static fields are shared by all objects of a class. Regardless of how many objects we create, there is only one instance of static variable for all objects. Same copy of a static field is accessed by all objects.

  • Static variables are initialized(gets memory) only once at the time of class loading. Static variables gets initialized before any object of that class can be created.

  • To access a static variable we don't have to create an object. We can access a static variable by using the name of the class.

  • Syntax to access static variables : .
Uses of Static Variables
  • We can use static variables to define class level constants. If we want all objects to share a constant value like rate of interest, value of PI(3.141), Number of students in class etc, then we declare it as a class level constant using static keyword.
  • Using static variables makes you program memory efficient as each object of class will share shame copy of static variables instead of creating it's own.

Static Methods

  • Like static variables, static methods also belongs to a class and not instances of class.

  • A static method can only access static variables and can only call other static methods of class. It cannot access non-static variables and methods.

  • A static method can be called without an object. Like static variables, we can invoke static methods using class name.

  • We cannot use "super" and "this" reference inside static method as we can invoke it without any object.
Uses of Static Methods
We use static methods to write a common utility methods to be use by everyone. Static methods are heavily used in writing a shared library.

Static Blocks

  • Static block is a code block inside class surrounded by { and } which gets executed once at the time of class loading.

  • Static blocks are used to initialize static variables.

  • Syntax of static block
    static {
    // static block statement 
    }
    

Points to remember about static keyword
  • A static variable and static method can be accessed without using creating objects.
  • static modifier cannot be applied to a class.
  • A static method can only access other static variables and methods of a class.
  • As static method cannot use super and this references.
  • Static Methods can not be overriden.