How Can You Reference Static Variables

Via reference to any instance of the class

Code:

Computer comp = new Computer ();

comp.harddisk where hardisk is a static variable

comp.compute() where compute is a method

To reference static variables in Java, you use the class name followed by the dot (.) operator and the variable name. Since static variables belong to the class rather than an instance of the class, you don’t need an instance of the class to access static variables.

Here’s an example:

java
public class MyClass {
public static int myStaticVariable = 42;
public static void main(String[] args) {
// Reference the static variable using the class name
int value = MyClass.myStaticVariable;

System.out.println(“The value of the static variable is: “ + value);
}
}

In this example, myStaticVariable is a static variable in the MyClass class. It is accessed using the class name MyClass followed by the dot operator.

Remember that static variables are shared among all instances of a class and can also be accessed without creating an instance of the class.