Static Variable in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

A static variable in Java is a class variable that belongs to the class rather than to any specific object. It is declared using the static keyword, which is a non access modifier in the Java programming language. Unlike an instance variable, which gets its own copy for every object, a static variable has only one copy for the entire class. That single value is shared across all the instances of the class.

Because a static variable is created once at the class level, it helps with memory efficiency. If one class instance changes the value of the same static variable, the updated new value becomes visible to all other instances. This is why static variables are useful when a common value must be shared across many objects.

A static variable can be accessed using the class name, and it can also be accessed through an object reference, although using the class name is the recommended style. Static variables are often used in counters, constants, utility values, configuration fields, and interview-based examples in Java interview questions.


What is a Static Variable in Java?

Let’s start this article with a real-life example. Consider a machine that produces different varieties of pens like blue, black, green, etc. for a company ‘X’.

All pens are different in their properties. Some are blue with different body structures, and some are black. But one attribute is common among all the pens: their company name, i.e., ‘X’.

Let's implement a class Pen incorporating the abovementioned details.

The companyName variable is of the static type, which implies that it is shared among all instances of the Pen class.

What is the purpose of declaring the companyName variable as static? It is because since the value of companyName variable is same for all the Pen objects, maintaining it separately for each instance is not memory efficient. Hence, the static variable is associated with the class rather than objects.

Static Variable in Java

  • The static variables are those that are common to all the class instances.
  • Only a single copy of the static variable is created and shared among all the class instances.
  • Because it is a class-level variable, memory allocation of such variables only happens once when the class is loaded in the memory.
  • If an object modifies the value of a static variable, the change is reflected across all objects.

What is the Use of static Keyword in Java?

The main use of the static keyword in Java is memory management. Whenever we place a static keyword before initialising a particular class’s methods or variables, these static methods and variables belong to the class instead of their instances or objects.

Syntax of Static Variable in Java

Syntax:

static variable in java data types Example: Country.java

Output:

Explanation:

  • In the example above, we have created a class Country with a static variable countryCounter.
  • We have created two objects: ob1 and ob2 of Country class and incremented the value of countryCounter using them.
  • Finally, we have accessed the value of the countryCounter variable in three different ways, and the value is the same as it can be seen in the output.
  • This shows the variable is shared across all instances and can be accessed using the class identifier.

Working on the above program diagrammatically.

During compilation of the Country.java file, the Java compiler binds the static variables to the class; in this case, the countryCounter variable is bound to the compiled class.

In the diagram below, we can see that the static variable countryCounter is linked to the class and shared among all class instances.

In this case, two instances of the country class are accessing the same static variable shown below in the diagram. Since the countryCounter variable is a static variable and static variable is a class variable so any changes in these variables are reflected among all the instances of the class, so after the first increment the value of countryCounter is 1 and after another increment, the final value is 2.

example of static variable in java

Storage Area of Static Variable in Java

The static variables and methods are stored in the heap memory. In fact, all static methods are stored in the Heap memory.

Before the Java 8 version, static variables of the class were stored in a separate section of the non-heap memory named Method Area created by the Java Virtual Machine after the class compilation. Method area section was used to store static variables of the class, metadata of the class, etc. Whereas, non-static methods and variables were stored in the heap memory.

storage area of static variable in java

How to Declare a Static Variable in Java

static variable in java are declared through the use of static keyword. The static keyword indicates to the JVM (Java Virtual Machine) that this variable should be loaded with the class during the compilation of the program.

If we don’t initialize the static variable, the default value of the static variable data type will be automatically assigned to it in Java. For example, the default value of integers is zero, objects is null, and so on.

Declaration Examples

Example:

Output:

Explanation:

  • If we don’t assign an initial value to any static variable, the default value is automatically initialized for that particular variable.
  • In the above example, there are static variables, one of which is a boolean type, and the second is an integer type.
  • We didn’t initialize these variables, so whenever we try to access them, we will get their default values: false for boolean type variables and 0 for integers. These are the default values for these data types.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Declaration Scope of the Static Variable in Java

We cannot declare static variables in the main() method or any kind of method of the class. The static variables must be declared as a class member in the class.

Because during compilation time, JVM binds static variables to the class level, which means they have to be declared as class members.

Example

Explanation:

  • In Java, static variables can be declared like class members, like static int number, which is a valid declaration of the static variable. However, static variables cannot be declared inside any method scope.
  • The compiler will show a syntax error if we try to declare static variables inside any method.
  • In the above example, if we try to declare a static variable in the main() method, the compiler will show an' illegal modifier' syntax error.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

Initialization of Static Final Variables in Java

The static variables are also used as constants with the final keyword in Java. Constants must be initialized and any kind of update is not allowed on them. Let’s understand this with an example.

  • Variables declared with static and final keywords must be initialized with a value.
  • Final variables cannot be modified as shown below.
  • In the above example, if we don’t initialize the static variables compiler will show an error during compilation time.
  • In the above program final static variable b is not initialized and hence it will throw an compile-time error.
  • The final keyword restricts any changes in the variable, so any kind of increment, decrement, or any other change will violate this restriction, and that’s why the compiler will show an error in the above case. The “a++” line is not a valid statement.

Accessibility of the Static Variable in Java

Static variables can be accessed by calling the class name of the class. There is no need to create an instance of the class for accessing the static variables because static variables are the class variables and are shared among all the class instances.

Accessibility of the Static Variable in Java

A static variable can be accessed in:

  • static methods

  • non static methods

  • We cannot access non-static variables in static methods because non-static variables can only be accessed by creating an instance of the class.

  • However, static methods can be called without creating an instance of the class.

  • This leads to reference error for the non-static variable because non-static variables can be accessed only through an instance of the class that’s why static methods cannot access non-static variables.

  • Another way of understanding this: If we have not created any instance of a class and call the static method which contains a non-static reference, which object should the non-static member point to?

Code:

Explanation:

  • In the above example, a non-static variable named number is called in two methods: one is a static method check() and the other is a non-static method i.e check1().
  • When the non-static variable is called inside check(), Java compiler will show a reference error because:
    • We can only access the non-static variable only after creating an instance of the class.
    • But static methods can be called without creating an instance of the class,
    • That’s why during accessing the non-static variable in the static method compiler will show reference error.

Syntax for Accessing

  • Classname: Name of the class containing the static variable.
  • (.) dot operator: Operator used to access static variables.
  • Variablename: Name of static variable that needs to be called. syntax for accessing

Example

Output:

Explanation:

  • In the above example, the static variable named ans is accessed in two ways. One way is without creating an instance of the class using the class reference only and the second way is using the instance of the class.
  • While accessing the static variable in java using the instance of the class, the compiler will show a warning: The static field Main.ans should be accessed in a static way.
  • This is because there is no need to create an instance of accessing the static members of the class.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

1. Common for all instances

The static variables are common for all the instances. A single copy of the static variables is shared among all the instances of the class. If any object of the class modifies the value of a static field, the modification is reflected across all instances.

Example

Output:

Explanation:

  • In the above example, a single copy of the static variable in java, i.e, number is shared among all the two instances of the class.
  • First instance named as ob1 increments the value of number variable by 1 and the second instance named as ob2 again increments the value of a static variable number by 1 finally making it 2,

Class containing static members and non-static members

Code:

Output:

  • In the above program, static variable insert() is called by every new instance of the class and it inserts the name for every new instance and increments the count_clicks variable.
  • Since a static variable is shared among all the instances, any changes done due to any instance automatically update its original state.
  • In the above program, we increment static members three times. Hence the output is 3. This value is same across all instances, which means changes done by any one instance is reflected across all instances. Use this Compiler to compile your Java code.

Memory Management of the above program

memory management in static variable in java

  • Whenever we create an instance of the class, a separate copy of all the class methods and variables except static members is created for all respective instances of the class in the heap memory.
  • In the above example the method name as insert() is called by the three instances of the class and each time insert() method is called the value of count_clicks is increment by one.
  • Since count_clicks is a static variable, it is shared among all the instances of the class, so any changes to this variable are reflected among all the instances of the class.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

A Real-Life Example of Static Variable in Java

  • The simplest real-life example of a static variable is supposed to have a class named Student that represents the details of any student who took admission to the school.
  • Now we have to count how many students were admitted to the school.
  • In this case, the concept of static variables in Java can be used. We simply create a static variable named count_student inside the Student class.
  • Increment the value of count_student inside the constructor for Student class. As a result, whenever we create a new instance of Student class, count_student will automatically increase by 1.
  • In this way, we can count the number of new students admitted to the school.

Important Points About Static Variable in Java

  • Static variables in Java are shared across all the instances of a class.

  • A static variable is associated with the class, not with a specific object.

  • Static variables are created when the class is loaded.

  • Static variables can be accessed inside static methods and non static methods.

  • A non static variable cannot be directly used inside a static method.

  • Static variables are memory efficient because they are created only once.

  • Static members should ideally be accessed using the class name.

  • A static variable is useful when the same value must be shared across the class


Conclusion

A static variable in Java is a class variable that belongs to the class rather than to any object. It is declared with the static keyword and is shared by all the instances of that class. Since there is only one copy of the variable, static fields are memory-efficient and ideal for storing shared data.

To summarize:

  • a static variable belongs to the class

  • it is created when the class is loaded

  • it is shared across all objects

  • it can be accessed using the class name

  • it is often used for counters, constants, shared values, and utility data

  • static methods can access static variables directly

  • non-static variables cannot be directly accessed inside a static method

If you understand static variables in Java, you also understand an important part of class level design, memory efficiency, and Java object behavior.


FAQs on Static Variable in Java

1. What is a static variable in Java?

A static variable in Java is a variable that belongs to the class rather than to any object. It is shared among all objects of that class.

2. Why do we use static variables in Java?

Static variables are used when the same value or shared data is needed for all objects. They improve memory efficiency because only one copy is created.

3. Can a static variable be accessed without creating an object?

Yes. A static variable can be accessed using the class name, without creating an object.

4. Can static methods access non-static variables?

No. A static method cannot directly access a non static variable because non-static variables belong to a specific object.

5. What is the default value of a static variable in Java?

If not initialized, a static variable gets the default value of its data type. For example, int gets 0, boolean gets false, and object references get null.

6. Can we declare a static variable inside main method?

No. Static variables must be declared at the class level. They cannot be declared inside the main method or any other method.

7. Is static variable a class variable?

Yes. A static variable is also called a class variable because it belongs to the class.

Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more