For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
In Java, variables are fundamental building blocks that store data and define the behavior of objects. However, not all variables function in the same way. One important type is the static variable, which is unique because it belongs to the class itself rather than any individual object. This means that all instances of the class share the same static variable, rather than each object having its copy.
Static variables are commonly used when a single, consistent value needs to be maintained across multiple objects, such as:
Unlike instance variables, which are created and destroyed with objects, static variables are initialized only once when the class is loaded into memory. This not only saves memory but also ensures data consistency across all instances of the class.
Java programming variables play a crucial role in storing and managing data. Among them, static variables stand out as a unique type that belongs to the class rather than any specific object. Unlike instance variables, which have separate copies for each object, static variables are shared across all instances. This makes them highly useful for scenarios where a common value needs to be maintained, such as counters, configuration settings, or constants. Understanding static variables is essential for efficient memory management and optimized code performance in Java applications.
Transform your Java knowledge into mastery with our Software Development courses — get ready to take your coding skills to new heights!
Static variables play a vital role in Java programming, offering efficiency, memory optimization, and consistency. Unlike instance variables, which are unique to each object, static variables are shared across all instances of a class. This makes them particularly useful in scenarios where a single, consistent value needs to be accessed and modified by multiple objects.
Why Static Variables are Important in Java:
Common Use Cases:
Example: static final double TAX_RATE = 0.18; used in an e-commerce application.
Static variables are essential for efficient memory usage, performance optimization, and maintaining global values across objects. However, they should be used wisely to avoid excessive data sharing, unintended modifications, or unnecessary memory retention. When used correctly, they make Java applications cleaner, more structured, and easier to manage.
Understanding the difference between static and instance variables helps in writing optimized Java code.
How Static Variables Differ From Instance Variables:
In Java, variables define how data is stored and accessed within a class. Static variables and instance variables serve different purposes, impacting memory management, accessibility, and behavior across objects.
Example Code: Static vs Instance Variables:
class Example {
static int staticVar = 10; // Static variable
int instanceVar = 20; // Instance variable
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
obj1.instanceVar = 30; // Changes instance variable for obj1
obj2.staticVar = 50; // Changes static variable for all objects
System.out.println("Object 1 - StaticVar: " + obj1.staticVar + ", InstanceVar: " + obj1.instanceVar);
System.out.println("Object 2 - StaticVar: " + obj2.staticVar + ", InstanceVar: " + obj2.instanceVar);
}
}
Output:
Object 1 - StaticVar: 50, InstanceVar: 30
Object 2 - StaticVar: 50, InstanceVar: 20
A static variable in Java is a class-level variable that is shared among all instances of the class. It is declared using the static keyword and belongs to the class rather than any individual object. This means that all objects of the class share the same copy of the static variable, ensuring memory efficiency and data consistency. A static variable is a variable declared using the static keyword within a class but outside any method, constructor, or block. It is stored in the class memory (Method Area) and is initialized only once when the class is loaded.
Also Read: What is Static Keyword in Java? Various Applications Explained
Declared Using the Static Keyword Inside a Class
The static variable is declared using the static keyword within a class. This makes the variable a class-level variable rather than an instance-level variable. Once declared, a static variable is shared across all instances of that class, meaning every object of that class accesses the same memory location for that variable.
About Declaring a Static Variable:
Static Keyword: The variable is explicitly marked with the static keyword to indicate it belongs to the class, not to an instance of the class.
Class-Level Access: Static variables are tied to the class itself, not any individual object created from that class.
Memory Allocation: A static variable is allocated memory only once, when the class is loaded into memory. This is in contrast to instance variables, which are allocated separately for each object.
Shared Among Objects: All objects of the class access the same value for a static variable. This makes it useful for keeping shared data.
In summary, the static keyword is a powerful tool for managing variables in Java, especially when the data needs to be shared or accessed globally across objects of the same class.
Shared Among All Instances of the Class
A static variable in Java is a class-level variable that is shared among all instances of the class. Unlike instance variables, which have a separate copy for each object, a static variable is stored in a single memory location and is accessible to every object of the class. Because static variables are shared among all instances, they are useful for scenarios where a single value needs to be accessed or updated by multiple objects. However, modifying static variables should be done cautiously, as changes affect all objects of the class.
One Copy for All Objects – The static variable is created only once and remains the same for all instances of the class.
Changes Affect All Instances – Modifying a static variable in one object reflects the change in all other objects.
Efficient Memory Usage – Since only one copy exists, it saves memory compared to instance variables, which require separate copies for each object.
Maintains Consistency – Ideal for situations where all objects need to refer to the same data (e.g., a global counter or a configuration setting).
Example: Demonstrating Shared Static Variable:
class SharedExample {
static int sharedCounter = 0; // Static variable shared across all objects
SharedExample() {
sharedCounter++; // Increments with every object creation
}
void display() {
System.out.println("Shared Counter: " + sharedCounter);
}
}
public class Main {
public static void main(String[] args) {
SharedExample obj1 = new SharedExample();
SharedExample obj2 = new SharedExample();
SharedExample obj3 = new SharedExample();
obj1.display(); // Output: Shared Counter: 3
obj2.display(); // Output: Shared Counter: 3
obj3.display(); // Output: Shared Counter: 3
}
}
How This Works:
Tracking the Number of Objects Created – Used in object counters, such as counting total users in an application.
Global Configuration Values – Useful for storing settings like database connection details or API keys. Logging and Debugging – Static variables in loggers ensure a single, shared logging instance. Mathematical Constants – Math.PI and other constants are shared across all instances.
Memory Allocation Occurs Only Once at Class Loading
A static variable is allocated memory only once, when the class is loaded into memory. Unlike instance variables, which are created separately for each object, static variables are stored in a single memory location and remain accessible throughout the program’s execution.
By understanding how static variables are allocated only once at class loading, developers can use them effectively to optimize memory usage and improve performance.
A static variable in Java has a class-level scope and a lifetime that lasts as long as the class is loaded in memory. Unlike instance variables, which are tied to objects, static variables exist independently of objects and are accessible from anywhere in the class.
Key Takeaways
Wide Scope – Available throughout the class and accessible via the class name.Long Lifetime – Stays in memory from class loading to class unloading.Independent of Objects – Does not depend on object creation or destruction.Efficient Memory Usage – Uses a single memory location, reducing redundancy.
Understanding the scope and lifetime of static variables helps in designing efficient and optimized Java applications, ensuring better memory management and data consistency.
Also Read: Types of Variables in Java: Java Variables Explained
A static variable in Java is declared using the static keyword and belongs to the class instead of an instance. It is shared among all objects of the class and can be accessed without creating an instance of the class.
class ClassName {
static dataType variableName = value;
}
Example: Declaring and Using Static Variables
class StaticExample {
static int count = 0; // Static variable
StaticExample() {
count++; // Increments for each object created
}
static void display() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
StaticExample obj1 = new StaticExample();
StaticExample obj2 = new StaticExample();
StaticExample.display(); // Output: Count: 2
}
}
How to Use Static Variables:
Accessing a Static Variable Using the Class Name:
System.out.println(StaticExample.count);
Accessing a Static Variable Inside Static and Non-Static Methods:
static void staticMethod() {
System.out.println(count); // Direct access in static method
}
void nonStaticMethod() {
System.out.println(count); // Direct access in non-static method
}
Modifying a Static Variable:
StaticExample.count = 10; // Changing the value directly using class name
Key Takeaways:
Code Snippet:
class Counter {
static int count = 0; // Static variable shared by all instances
Counter() {
count++; // Increments when a new object is created
}
void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter obj1 = new Counter(); // count = 1
Counter obj2 = new Counter(); // count = 2
Counter obj3 = new Counter(); // count = 3
obj1.displayCount(); // Output: Count: 3
obj2.displayCount(); // Output: Count: 3
obj3.displayCount(); // Output: Count: 3
}
}
Explanation:
Key Takeaways:
In Java, a static variable is shared among all instances of a class. This means that if one object modifies the static variable, the change is reflected across all objects because only one copy of the variable exists in memory.
Demonstrating Value Retention:
class Counter {
static int count = 0; // Static variable (shared across all objects)
Counter() {
count++; // Increments count whenever a new object is created
}
void displayCount(String objectName) {
System.out.println(objectName + " Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter obj1 = new Counter(); // count = 1
obj1.displayCount("obj1");
Counter obj2 = new Counter(); // count = 2
obj2.displayCount("obj2");
Counter obj3 = new Counter(); // count = 3
obj3.displayCount("obj3");
}
}
Static variables in Java are class-level variables that are shared across all instances of a class. They are allocated memory only once and can be accessed using the class name, making them ideal for storing constants and shared data.
A static variable in Java is allocated only once, regardless of how many objects are created. It resides in the Method Area (Class Area) of memory and is shared among all instances of the class.
Demonstrating Single Memory Allocation:
class StaticMemory {
static int count = 0; // Static variable (shared across all objects)
StaticMemory() {
count++; // Increments count whenever a new object is created
}
void display(String objName) {
System.out.println(objName + " Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
StaticMemory obj1 = new StaticMemory(); // count = 1
obj1.display("obj1");
StaticMemory obj2 = new StaticMemory(); // count = 2
obj2.display("obj2");
StaticMemory obj3 = new StaticMemory(); // count = 3
obj3.display("obj3");
}
}
Output:
obj1 Count: 1
obj2 Count: 2
obj3 Count: 3
Can Be Accessed Using the Class Name (e.g., ClassName.variableName)
A static variable in Java belongs to the class rather than any specific object. This allows it to be accessed directly using the class name, without needing to create an instance of the class.
class StaticExample {
static int count = 10; // Static variable
static void display() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
// Accessing static variable using class name
System.out.println("Accessing directly: " + StaticExample.count);
// Calling static method using class name
StaticExample.display();
}
}
Output:
Accessing directly: 10
Count: 10
Alternative Access Through Objects (Not Recommended)
StaticExample obj = new StaticExample();
System.out.println(obj.count); // Works, but not recommended
A static variable is associated with the class itself, not with individual objects. This means that all instances of the class share the same static variable rather than having separate copies.
A static variable belongs to the class:
class Student {
static String schoolName = "Greenwood High"; // Static variable
String studentName;
Student(String name) {
this.studentName = name;
}
void display() {
System.out.println(studentName + " studies at " + schoolName);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
// Display values for both students
s1.display();
s2.display();
// Changing the static variable using class name
Student.schoolName = "Sunrise Academy";
// Display updated values
s1.display();
s2.display();
}
}
Output:
Alice studies at Greenwood High
Bob studies at Greenwood High
Alice studies at Sunrise Academy
Bob studies at Sunrise Academy
Useful for constants and shared data:
Static variables are ideal for storing constant values and shared data that remain the same across multiple instances of a class. This ensures efficient memory usage and maintains data consistency throughout the program.
class AppConfig {
static final String APP_NAME = "HealthTracker"; // Constant (Shared across all instances)
static int activeUsers = 0; // Shared data (Tracks active users)
AppConfig() {
activeUsers++; // Increments when a new user is created
}
static void displayAppInfo() {
System.out.println("App: " + APP_NAME);
System.out.println("Active Users: " + activeUsers);
}
}
public class Main {
public static void main(String[] args) {
// Accessing constant using class name
System.out.println("Application Name: " + AppConfig.APP_NAME);
// Creating users
AppConfig user1 = new AppConfig();
AppConfig user2 = new AppConfig();
AppConfig user3 = new AppConfig();
// Displaying shared data
AppConfig.displayAppInfo();
}
}
Output:
Application Name: HealthTracker
App: HealthTracker
Active Users: 3
Static and instance variables are two key types of variables in Java, each serving different purposes. While static variables are shared across all instances of a class, instance variables are unique to each object. The table below highlights their key differences.
Feature | Static Variable | Instance Variable |
Memory Location | Stored in the Method Area (Class Area), allocated once per class. | Stored in the Heap Memory, allocated separately for each object. |
Shared Among Instances | Yes – One copy is shared across all objects of the class. | No – Each object gets its own separate copy. |
Requires an Object for Access | No – Can be accessed using the class name (ClassName.variableName). | Yes – Must be accessed through an object (objectName.variableName). |
Lifetime | Exists as long as the class is loaded in memory. | Exists as long as the object exists. |
Static variables in Java can be used within static methods and blocks, enabling efficient data sharing and initialization at the class level.
Static variables can be accessed directly inside static methods because both belong to the class rather than an instance. This eliminates the need to create an object to access static variables within static methods.
Code:
class Company {
static String companyName = "Tech Innovators"; // Static variable
// Static method accessing the static variable
static void displayCompany() {
System.out.println("Company Name: " + companyName);
}
}
public class Main {
public static void main(String[] args) {
// Calling static method without creating an object
Company.displayCompany();
}
}
Output:
Company Name: Tech Innovators
In Java, non-static methods can access static variables without any restrictions. Since static variables belong to the class (not instances), all objects of the class share the same value. A non-static method can directly refer to static variables because it belongs to an instance of the class, which has access to class-level variables.
Code:
class Employee {
static String companyName = "Tech Solutions"; // Static variable
String employeeName; // Instance variable
// Constructor to initialize instance variable
Employee(String name) {
this.employeeName = name;
}
// Non-static method accessing static variable
void displayDetails() {
System.out.println(employeeName + " works at " + companyName);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects
Employee emp1 = new Employee("Alice");
Employee emp2 = new Employee("Bob");
// Accessing static variable inside non-static method
emp1.displayDetails();
emp2.displayDetails();
// Changing static variable's value
Employee.companyName = "NextGen Tech";
// Accessing updated value
emp1.displayDetails();
emp2.displayDetails();
}
}
Output:
Alice works at Tech Solutions
Bob works at Tech Solutions
Alice works at NextGen Tech
Bob works at NextGen Tech
Static variables are widely used in software development to manage shared resources, store constants, and optimize memory usage. Here are some common real-world applications:
Example:
class Config {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mydb";
static final int TIMEOUT = 30;
}
Static variables can be powerful, but improper use can lead to bugs, memory issues, and design flaws. Here are some common mistakes and how to avoid them:
Q: What is a static variable in Java?
A: A static variable is a class-level variable shared by all instances of the class. And It is declared using the static keyword inside a class but outside any method.
Q: How does a static variable differ from an instance variable?
A: Static Variable: Belongs to the class, shared among all objects, and stored in the class memory. Instance Variable: Each object gets its own copy, and it is stored in the heap memory.
Q: Where are static variables stored in memory?
A: Static variables are stored in the Method Area (Class Area) of the JVM memory. They are allocated only once when the class is loaded and deallocated when the program ends.
Q: Can we access a static variable inside a non-static method?
A: Yes! A non-static method can access a static variable directly because static variables belong to the class.
Q: What are the best use cases for static variables?
A: Storing constants (static final double PI = 3.14159;).
Maintaining a global counter for tracking instances.
Database configurations or shared application settings.
Utility methods in helper classes where object creation is unnecessary.
Also Read: Top 22 Open Source Java Projects to Enhance Your Development Skills
In Java, static variables belong to the class rather than any individual object, meaning they are shared across all instances. This allows for maintaining a common state between objects. In this exercise, we will implement a counter using a static variable that tracks the number of objects created from a class. Since the variable is shared, its value persists across multiple object creations, making it ideal for tracking instances or global counts.
Static variables help in scenarios where data consistency across instances is required, such as maintaining a total count of users in an application or generating unique IDs. Unlike instance variables that are tied to individual objects, a static variable updates its value across all objects, ensuring a synchronized count. We will also use a static method to access the static counter, since static methods can interact only with static members.
Code:
// Counter class with a static variable
class Counter {
private static int count = 0; // Static variable to keep track of object count
public Counter() {
count++; // Increment the counter when a new object is created
}
public static int getCount() {
return count; // Return the current count
}
}
// Main class to test the Counter
public class StaticCounterExample {
public static void main(String[] args) {
// Creating multiple objects
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter obj3 = new Counter();
// Display the total count of objects created
System.out.println("Number of Counter objects created: " + Counter.getCount());
}
}
Explanation:
Output:
Number of Counter objects created: 3
Key Takeaways:
This approach is useful for tracking instances, unique IDs, or global counters in Java applications.
In Java, static constants are variables declared using the static and final keywords. A static variable belongs to the class rather than an instance, while final ensures the value remains unchanged throughout execution. This prevents modifications and allows shared access across multiple objects. In this exercise, we will create a program to store and access a static constant, demonstrating how to define and retrieve global constants efficiently.
Using static constants improves code maintainability and readability by preventing accidental modifications of important values like mathematical constants, configuration settings, or fixed thresholds. Unlike regular instance variables, static constants can be accessed without creating an object, using ClassName.CONSTANT_NAME. This approach follows best practices for defining shared values, reducing redundancy, and ensuring consistency across multiple parts of a program.
Code:
// Define a class with a static constant
class Constants {
// Static final variable (constant)
public static final double PI = 3.14159;
public static final String APP_NAME = "MyJavaApp";
}
// Main class to access the static constant
public class StaticConstantExample {
public static void main(String[] args) {
// Accessing static constants without creating an object
System.out.println("Application Name: " + Constants.APP_NAME);
System.out.println("Value of Pi: " + Constants.PI);
}
}
Explanation:
Output:
Application Name: MyJavaApp
Value of Pi: 3.14159
Key Takeaways:
This approach is widely used in real-world applications to store configuration settings, API keys, tax rates, and mathematical constants.
In Java, a static block is used to initialize static variables before the execution of the main method. Static variables belong to the class rather than instances, meaning their values remain shared across all objects. A static block runs only once when the class is loaded, making it ideal for performing setup operations like loading configurations, initializing constants, or establishing database connections.
This approach ensures that static variables are properly initialized before use. Unlike instance variables that get initialized within a constructor, static variables cannot rely on constructors since they are independent of object creation. Using a static block, we can set their values dynamically at runtime, even before any object of the class is created.
Code:
// Class demonstrating static variable initialization with a static block
class StaticBlockExample {
// Static variable
static int count;
// Static block to initialize the static variable
static {
System.out.println("Static block executed.");
count = 100; // Initializing static variable
}
// Method to display the value of count
public static void displayCount() {
System.out.println("Count: " + count);
}
}
// Main class to execute the program
public class StaticBlockDemo {
public static void main(String[] args) {
// Access static method to display the initialized value
StaticBlockExample.displayCount();
}
}
Explanation:
Output:
Static block executed.
Count: 100
Key Takeaways:
This technique is widely used in frameworks, singleton patterns, and database connections to set up shared resources before execution starts.
Static variables are an essential part of Java programming, helping developers manage shared data efficiently, optimize memory usage, and improve performance. Whether you're building scalable applications, handling configurations, or implementing design patterns, understanding static variables is crucial for writing clean and maintainable code.
If you want to deepen your understanding of Java and gain hands-on experience, explore upGrad’s industry-relevant courses like:
Their structured curriculum, real-world projects, and expert guidance will help you master Java, advance your programming skills, and boost your career prospects.
To get guidance and support avail the free counselling session from our experts today!
Similar Reads:
Ans: Static variables are stored in the Method Area (also known as the Class Area) of the Java Virtual Machine (JVM) memory. They are allocated when the class is loaded and deallocated when the class is unloaded.
Ans: Yes, static variables can be modified in Java, but they are shared among all instances of the class. Any changes made to a static variable will affect all objects of that class since they reference the same memory location.
Ans: Static variables do not get garbage collected as long as the class that defines them is loaded in memory. Since static variables are tied to the class itself and not to specific instances, they remain in memory for the duration of the program's execution.
Ans: Yes, static variables can be accessed in non-static methods without any issues. Since static variables belong to the class and not to a specific instance, they are accessible from both static and non-static methods.
Ans: If static variables are not used, each object will have its own copy of the variables. This might not be efficient if you need shared data across all instances. Without static variables, you'll lose the ability to share common data or manage class-level information.
Ans: A static variable is shared among all objects because it belongs to the class itself, not to individual instances. When a class is loaded into memory, only one copy of the static variable is created and shared across all instances, saving memory and ensuring consistency across objects.
Ans: Static variables in Java are initialized when the class is loaded into memory, before any object is created. They are initialized either with their default values (e.g., 0 for integers, null for objects) or with explicit values if provided. Initialization occurs only once during the class loading process.
Ans: Yes, you can use final with static variables in Java. A final static variable is a constant that can be assigned a value only once, either at the time of declaration or in a static block. Once initialized, its value cannot be changed.
Ans: The default value of a static variable in Java depends on its data type. For primitive types, the default values are:
0 for numeric types (e.g., int, long, float, double)
False for boolean
null for reference types (e.g., String, objects)
These default values are assigned when the class is loaded, before any explicit initialization.
Ans: In multithreading, static variables are shared across all threads because they belong to the class itself, not to individual instances. This can lead to thread safety issues if multiple threads attempt to modify a static variable concurrently.
To prevent problems such as race conditions, you can use synchronization techniques or Atomic variables (e.g., AtomicInteger) to ensure safe access and modification of static variables in multithreaded environments.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.