Static Variables in Java – A Complete Overview with Examples

Updated on August 26, 2024

Article Outline

Java has three kinds of variables: instance, local, and static. The instance variables belong to the individual objects, while the static ones are attached to the class. All the class objects will share a static variable and contain one single copy, no matter how many instances you may create. Let’s explore static variables in Java in detail!

What is a Static Variable in Java?

A Java static variable is shared among all the class instances. Whereas instance variables are unique to every object, a static variable does not belong to any particular instance but rather to the class itself. Changes made to a static variable by any instance are reflected across all class instances. Static variables store data that should be common to all class objects rather than unique to each instance.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Initialization of Static Final Variables in Java

Java Developer also used a static variable as a constant with the final keyword. Constants must be initialized during the declaration. It means the declaration cannot be changed after being assigned.

 

The following program demonstrates the Initialization of static final variables in Java language.

 

Program

class Main{ static final int a = 350 ; static final int b ; public static void main(String args[]){ System.out.println(a); a++ ; } }

Output

Main.java:9: error: cannot assign a value to final variable a a++ ; ^ 1 error

Properties of Static Variables

Static variables in Java have several distinct properties that differentiate them from instance variables. Here are the key properties.

 

  • Class-Level Scope: Static variables are associated with the class rather than any particular instance. This means that they are shared across all instances of the class.

 

  • Single Copy: There is only one copy of a static variable, regardless of the number of objects created from the class. All objects share the same copy of the static variable.

 

  • Memory Allocation: Static variables are allocated memory only once when the class is loaded into memory by the Java ClassLoader. They are stored in the method area of the memory, also known as the ‘class area.’

 

  • Default Values: Static variables are initialized to their default values if not explicitly initialized. A static int variable will be initialized to ‘0’, a static boolean will be ‘false,’ and so on.

 

  • Scope: The scope of static variables is very limited to the class in which it is declared. Its visibility to others depends on its access modifiers (e.g., ‘public’ and ‘protected’).

 

  • Inheritance: Static variables are inherited by a subclass, but each subclass shares the same copy of the static variable as the parent class.

 

  • Access: Static variables can be accessed using the className. We can also access the static variable using a class instance.

Storage Area of Static Variable in Java

The static variable and method are stored in the heap memory. It is a specific part of the heap memory dedicated to storing class-level information. When a class is loaded by the JVM, its static variables are allocated memory in this method area, which is shared across all class instances. This ensures that static variables are initialized once and accessed directly through the class name rather than individual object instances.

Storage Area of Static Variable in Java

How to Declare a Static Variable in Java?

We can declare a static variable through the use of a static keyword. Static variables belong to the class rather than to any specific class instance. This means that all instances of the class share the same static variable.

 

Declaration of Static Variables

static int number = 34; static int number; Static int number = 2;

The following program demonstrates the static variable in Java.

 

Program

class Main{ static boolean check ; static int number ; static int answer = 90 ; public static void main(String args[]){ System.out.println(Main.check); System.out.println(Main.number) ; System.out.println(Main.answer) ; } }

Output

false 0

 

Accessibility of the Static Variable in Java

In Java, a static variable is associated with a class rather than a class instance. There is no need to create an object to access the static variables because static variables are the class variables, and static variables are shared among all the class instances. Simply, we can access the static variable using the class name. (eg, ‘ClassName.variableName’).

Syntax for Accessing Static Variable ClassName.VaraibleName ; object.VariableName
  • ClassName: The name of the class that contains the static variable.
  • Dot Operator: Operator used to access static variables.
  • VariableName: The name of the static variable that needs to be called in a Java program.

 

The following program demonstrates the accessibility of static variables.

 

Program

public class Main { static int ans = 343; public static void main(String[] args) { System.out.println(Main.ans); Main ob = new Main(); System.out.print(ob.ans); } }

Output

343 343

 

What is the Use of Static Keywords in Java?

The ‘static’ keyword in Java is primarily used for memory management and to define class-level elements.

 

  • Class-Level Variables: Static variables are also known as class variables because they belong to the class rather than any specific class instance. This means that all instances of the class share the same static variable.

 

  • Memory Efficiency: Static variables are shared across all instances. Memory allocation for these variables happens only once, making the program more memory-efficient.

 

Syntax of Static Variable in Java

 

static datatype variableName = Value;

 

The following program demonstrates the static variable in Java.

 

 

Program

class Country { static int countryCounter = 0; String name; int dummyCounter; Country(String name, int dummyCounter) { this.name = name; this.dummyCounter = dummyCounter; } } class CountryManager { static Country createCountry(String name, int dummyCounter) { Country.countryCounter++; return new Country(name, dummyCounter); } }  public class Main { public static void main(String[] args) { Country ob1 = CountryManager.createCountry("India", 1); Country ob2 = CountryManager.createCountry("France", 1);  System.out.println("ob1.countryCounter = " + ob1.countryCounter); System.out.println("ob2.countryCounter = " + ob2.countryCounter); System.out.println("Country.countryCounter = " + Country.countryCounter); } }

Output

ob1.countryCounter = 2 ob2.countryCounter = 2 Country.countryCounter = 2

Real-world Example of Static Variable in Java

 

An example of a static variable in real life is the use of a static counter in Java to define how many times an object was instantiated from a class. The situation occurs whenever the course of the execution of a program is to be observed in terms of the number of instances of a given class.

 

The following program demonstrates a real-life example in Java.

 

Program

 

class Main { public static void main(String[] args) { Vehicle car = new Vehicle(); Vehicle bike = new Vehicle(); Vehicle truck = new Vehicle();   System.out.println("Total vehicles created: " + Vehicle.getVehicleCount()); } }   class Vehicle { private static int vehicleCount = 0;   public Vehicle() { vehicleCount++; }   // Static method to access the static variable public static int getVehicleCount() { return vehicleCount; } }

Output

Total vehicles created: 3

Conclusion

 

Static variables in Java are an essential aspect of class-level data management. They can save on memory, as they are shared across all instances of the class, but allow easy access to common values. Thus, a Java programmer should understand how to declare, initialize, and use static variables. With their ability to maintain a single copy of a variable for all objects, static variables help in scenarios where a standard resource or configuration is needed. This concept is fundamental for any Java developer looking to write clean and optimized source code.

FAQs
A static variable is declared using the ‘static’ keyword before the variable type for example .   Static int count ;
Use a static variable when you need to share a variable among all instances of a class or when the variable's value needs to be common and consistent across different objects.  
Yes, After declaring the static variable with the final keyword. Then, we cannot change the value of the static variable.  
The lifetime of a static variable is the same as the lifetime of the class in which it is declared. It is created when the class is loaded and remains until it is unloaded.
Yes, We can define a static variable as a private variable using the access modifier, including ‘private.’ However, they will only be accessible within the class where they are declared. 

Updated on August 26, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved