What is static variables in Java with examples?

When a variable is declared static, a copy of the variable is created and shared among all class-level objects. Static variables are basically global variables. All class instances use the same static variables.

Important points for static variables:

  • We can only create static variables at class level.
  • Static blocks and static variables are executed in the order they appear in the program.

Below is a Java program showing that static blocks and static variables are executed in the order they are in the program.

In Java, a static variable is a variable that is shared by all instances of a class. This means that the value of a static variable is the same for all objects of a class. Static variables are also known as class variables because they are associated with the class and not with any particular instance of the class.

To declare a static variable in Java, you use the "static" keyword before the variable declaration. Here is an example: 

 

public class MyClass {
    static int myStaticVariable = 42;
}

In this example, the variable "myStaticVariable" is declared as static. This means that its value will be the same for all instances of the class MyClass.

Static variables are commonly used to store values that are shared across all instances of a class, such as constants or configuration settings. For example: 

 

public class MathUtils {
    public static final double PI = 3.14159265359;
}

In this example, the constant "PI" is declared as a static variable. This means that the value of PI will be the same for all instances of the MathUtils class.

Static variables can also be accessed without creating an instance of the class, using the class name followed by the variable name. For example: 

 

int myValue = MyClass.myStaticVariable;

In this example, the value of the static variable "myStaticVariable" is accessed using the class name "MyClass".

Submit Your Programming Assignment Details