What is Static Variable in Java?
A static variable in Java belongs to a class and is shared among all instances of that class. It is declared using the “static” keyword before the variable type. It’s used to maintain common data across objects of the same class and can be accessed without creating an instance of the class.
Write a Java Program to Demonstrate Usage of a Static Variable x in the Test Class.
Here we made a variable X as a static variable and if we try to access that from main() directly then it will not show any error and executed. It proves that all static things of a class always belong to a class. Thus, keep those properties of an object as a static whose values are same from each instance of an object.
Here is the source code of the Java Program to Demonstrate Usage of a Static Variable x in the Test Class. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
/*
* Static Variable Program in Java
*/
public class Test
{
static int x = 17;
public static void main(String...a)
{
System.out.println(x); //static variable can be called directly
System.out.println(Test.x); //static variable can be called with class its name
}
}
1. This program demonstrates that static variables can be accessed directly using their name or through the class name.
2. The program contains a static variable called “x” that is declared as an integer with a value of 17.
3. In the main method of the program, the value of “x” is printed twice using the System.out.println() method.
4. The first time, the static variable “x” is called directly using its name.
5. The second time, the static variable “x” is called using the class name and the static variable name separated by a dot, like this: “Test.x“.
$ javac Test.java $ java Test 17 17
To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.
- Practice BCA MCQs
- Check Java Books
- Practice Information Technology MCQs
- Apply for Computer Science Internship
- Apply for Java Internship