Static Variable Program in Java

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.

Problem Description

Write a Java Program to Demonstrate Usage of a Static Variable x in the Test Class.

Problem Solution

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.

Program/Source Code

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.

  1. /*
  2.  * Static Variable Program in Java
  3.  */
  4.  
  5. public class Test
  6. {
  7.     static int x = 17;
  8.     public static void main(String...a)
  9.     {
  10.         System.out.println(x);   //static variable can be called directly
  11.         System.out.println(Test.x); //static variable can be called with class its name
  12.     }
  13. }
Program Explanation

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“.

advertisement
Program Output
$ 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”.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.