Search code examples
javavariablesglobal-variablesclass-variables

What is the difference between a class variable and a global variable?


Is there even any difference? Are they just different terms? I need to be able to explain the difference on school and what i wrote below seems like what the internet describes as a global variable.

Here's my code:

public class variableTypes

{
    public static String a = "hello!"; //<--- global variable (i think)

public static void main(String[]args)
{
  System.out.println(variableTypes.a);
}

Solution

  • Something that is static can be accessed by any class or method in the same namespace. Static variables will persist for the lifetime of the program.

    Something that is local to a class, will only exist for the lifetime of an instance of that class (an object), and can only be accessed through the instance.

    Something that is local to a function/method, will only exist for the execution of that method.

    It's the difference between:

    • i = Class.variable
    • i = myClass.variable
    • i = myClass.Function() if the function was something simple like int apple = 4; return apple otherwise, there isn't really a way to access variables local to a method/function.

    Note: I've ignored access modifiers, but let's just say this holds true given everything is public. Otherwise, every thing I say only mostly holds true with some extra work. (Probably better practice too.)

    Disclamer: I've used Java before, but it's not something I use regularly. But the concepts are pretty standard.

    Disclamer: I'm a student too, I can be wrong, but I think I'm right.

    I found this site, which seems to kinda back up what I'm saying: https://www.guru99.com/java-static-variable-methods.html

    The relevant-ish part in case the site goes offline:

    Java static variable It is a variable which belongs to the class and not to object(instance) Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables A single copy to be shared by all instances of the class A static variable can be accessed directly by the class name and doesn’t need any object Syntax : .

    Good luck!