Search code examples
javavariablesstaticstatic-variablesclass-variables

Are class variables and static variables same in Java?


I am aware that class variables are static and are shared among all the objects of that class. If that is the case, I am not sure what static variable is.

Furthermore, Wikipedia states class variables are not to be confused with static variables.


Solution

  • If I understand, you ask for the difference between:

    int a;
    

    and

    static int a;
    

    if both are defined as class variables (they are not inside a method) the main practical differences are scope and lifetime.

    A static variable will never be removed from memory and (if set public) will be accessible from anywhere in your project.

    The main description of the static modifier is that it detaches from the class, so:

    You don’t need to instantiate any object to use a static method.

    You don’t need to instantiate any object to get a static variable.

    You cant access non-static class variables inside a static method (basically you cant use "this")

    Hope this helps.