What is the difference between static and non-static variables

A static variable is associated with the class as a whole rather than with specific instances of a class.

Non-static variables take on unique values with each object instance.

In Java, the terms “static” and “non-static” are used to describe different types of variables and methods. Here’s the difference between static and non-static variables:

  1. Static Variables:
    • Also known as class variables.
    • Declared using the static keyword.
    • Belongs to the class rather than any specific instance of the class.
    • Shared among all instances of the class.
    • Initialized only once, typically in a static block or at the time of declaration.
    • Can be accessed using the class name (e.g., ClassName.variableName).

    Example:

    java
    class Example {
    static int staticVariable = 10;
    }
  2. Non-Static Variables:
    • Also known as instance variables.
    • Declared without the static keyword.
    • Belongs to a specific instance of the class.
    • Each instance of the class has its own copy of non-static variables.
    • Initialized when an object is created.
    • Accessed using the reference to the object.

    Example:

    java
    class Example {
    int nonStaticVariable = 20;
    }

In summary, the main difference lies in the scope and lifetime of the variables. Static variables are shared among all instances of a class and are initialized only once, while non-static variables belong to a specific instance of the class and are initialized when an object is created.