best practice about declaring a variable as static vs non static

by Parameswar   Last Updated June 12, 2019 07:26 AM - source

I have a java class where there are local variables,

private final String name;

is there an advantage of using static ?

static final name;

Both works, but what i was thinking is, when a read only object is shared between classes, it makes sense to create static object , Thoughts ?

Tags : java static


Answers 1


As the comments suggested, you might want to look at a tutorial to grasp the fundamental difference of a static variable versus a non-static variable.

The condensed effects are...

1: ... static variables can be accessed without creating an instance of that class and non-static variables cannot. This is because non-static variables need an instance of that class to be set, because they can differ from instance to instance, while static variables, like File.separatorChar are class-specific.

2: ... non-static variables cannot be accessed from within static methods. That means this works:

static int countInstances = 0;
int myID;

public Spielwiese() {
    countInstances++;
    myID = countInstances;
}

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

While this does not compile:

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

This is because the static method can only access static variables, ergo it is not bound to one specific instance. Therefore it cannot refer to variables that are only set in instances (which are all non-static variables).

3: ... the content of a static variable will be the same for multiple instances. Example:

static int countInstances = 0;
public TestClass() {
    countInstances++;
    System.out.println(countInstances);
}

public static void main(String[] args) {
    new TestClass();
    new TestClass();
}

This will have the output of 1 and 2. Both times the counter is increased, and since the variable is not with one of the instances but with the class itself, its content is updated for each instance when it is accessed.

Dennis Kühn
Dennis Kühn
June 12, 2019 07:25 AM

Related Questions



Race condition in variable in a static method

Updated May 07, 2017 03:26 AM