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
Variables are essential for storing and manipulating data in programming. However, there are scenarios where a variable needs to retain its value across different instances of a class or doesn't rely on an instance at all.
This is where static variables in Java, also called class variables, become useful. Unlike instance variables specific to objects, static variables are linked to the class. Learn more about the use case of static variables here.
In this tutorial, we will delve into the concept of the static variable in Java, understand their behavior, and explore how to declare, initialize, and use them effectively.
The static keyword in Java declares a class member (such as a variable or method) associated with the class itself instead of a particular instance of the class. By marking a member as static, it becomes accessible and functional without requiring the creation of an object from the class.
When a variable is declared static, it is called a static variable or class variable. These variables are shared by all instances of the class, meaning they maintain the same value across different objects. Static variables are declared using the syntax:
static dataType variableName;
Some advantages of using static variables in Java are:
public class StaticVariableExample {
// Static variable
public static int count = 0;
public static void main(String[] args) {
// Accessing and modifying the static variable
System.out.println("Initial count: " + count);
count++;
System.out.println("Updated count: " + count);
// Creating multiple objects of the class
StaticVariableExample obj1 = new StaticVariableExample();
StaticVariableExample obj2 = new StaticVariableExample();
// Accessing the static variable using different objects
obj1.count++;
obj2.count++;
System.out.println("Count after incrementing through objects: " + count);
}
}
In the above example, we have a class called StaticVariableExample with a static variable called count. The main method is the entry point of the program.
Inside the main method, we first print the initial value of count (which is 0), then we increment it by 1 and print the updated value.
Next, we create two objects of the class (obj1 and obj2) and increment the count variable using these objects. Since count is a static variable, it is shared among all instances of the class. Therefore, modifying it using one object affects the value seen by other objects and the class itself.
Finally, we print the final value of count, which is incremented by both the direct access and the access through objects, demonstrating the shared nature of the static variable.
In this example, the Counter class represents a simple counter. It has an instance variable count which stores the current count. The class provides methods to increment, decrement, and retrieve the count.
In the main method, we create an instance of the Counter class called counter. We print the initial count, which is 0. Then, we increment the count twice and decrement it once. Finally, we print the final count.
public class Counter {
private static int count;
public Counter() {
count = 0;
}
public static void increment() {
count++;
}
public static void decrement() {
if (count > 0) {
count--;
}
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
System.out.println("Initial count: " + getCount());
increment();
increment();
decrement();
System.out.println("Final count: " + getCount());
}
}
Now, in this program, the Counter class uses a static variable count to represent the counter. The methods increment(), decrement(), and getCount() are also defined as static.
In the main method, we directly access the static methods and variables without creating an instance of the Counter class. We print the initial count, which is 0. Then, we increment the count twice and decrement it once. Finally, we print the final count.
A static method in Java is associated with the class rather than instances of the class. Static methods can be called directly using the class name without creating an object. They are often used for utility functions or operations that don't require access to instance-specific data.
Static methods are declared using the syntax:
static returnType methodName(parameters);
public class StringUtils {
public static String reverseString(String str) {
StringBuilder reversed = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversed.append(str.charAt(i));
}
return reversed.toString();
}
public static void main(String[] args) {
String original = "upGrad teaches programming!";
String reversed = StringUtils.reverseString(original);
System.out.println("Original string: " + original);
System.out.println("Reversed string: " + reversed);
}
}
The StringUtils class contains a static method called reverseString that takes a string as a parameter and returns the reversed version of the string. In the main method, we create a string variable called original and assign it the value "upGrad teaches programming!". We then call the reverseString method and pass in original as the argument. The returned reversed string is stored in the reversed variable, and both the original and reversed strings are printed to the console.
The reverseString method is declared static, meaning it belongs to the class itself and can be accessed without creating class instances. Static methods are commonly used for utility functions or operations that do not require access to instance-specific data. In this example, the reverseString method operates solely on its input parameter str and does not rely on any instance variables.
public class MathUtils {
public static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = MathUtils.sum(5, 3);
System.out.println("The sum is: " + result);
}
}
The MathUtils class contains a static method called sum that takes two integers as parameters and returns their sum. In the main method, we call the sum method and pass in the values 5 and 3. The returned sum is stored in the result variable, and then we print it to the console.
The sum method is declared static using the static keyword. Static methods can be called directly on the class without creating an object of the class. In this example, we call the sum method using the class name MathUtils.sum().
Static methods in Java have the following restrictions:
In addition to variables and methods, Java also allows the creation of static blocks. A static block is a set of statements enclosed in curly braces and preceded by the "static" keyword in Java. It is executed when the class is loaded into memory and is commonly used for static initialization tasks.
The MyClass class contains a static block that is executed only once when the class is first loaded into memory. In this example, the static block initializes the static variable count to 0 and prints a message to the console.
The MyClass also has a constructor called each time an object of the class is created. In the constructor, the count variable is incremented.
In the main method, two objects of MyClass are created, which triggers the execution of the static block only once. After creating the objects, the getCount static method is called to retrieve the value of the count variable, which is then printed to the console.
Using a static block, you can execute a program without a main() method. When the Java ClassLoader loads the class into memory, it is commonly used for static initialization tasks. By placing the desired code within a static block, it will be executed without the need for a main() method.
To efficiently use static variables in Java, keep these important pointers in mind:
Static variables in Java are stored in a special area of memory called the "Method Area" or "Class Area". This area is shared by all class instances and is allocated when the class is loaded into memory. Static variables exist for the entire program duration and are accessible by all class instances.
Static final variables, also known as constants, are initialized at the time of declaration or in a static block. Once initialized, their values cannot be changed. The initialization of static final variables is typically done at the class level and is performed only once when the class is loaded into memory.
The differences between static and non-static variables have been elucidated below:
public class upGradTutorials {
private static int staticVariable; // Static variable
private int nonStaticVariable; // Non-static variable
public static void staticMethod() {
System.out.println("This is a static method.");
}
public void nonStaticMethod() {
System.out.println("This is a non-static method.");
}
public static void main(String[] args) {
staticVariable = 10; // Accessing the static variable
staticMethod(); // Calling the static method
upGradTutorials obj = new upGradTutorials();
obj.nonStaticVariable = 20; // Accessing the non-static variable
obj.nonStaticMethod(); // Calling the non-static method
}
}
When the class upGradTutorials is loaded into memory, the static variable staticVariable is allocated memory in the static data area, and the static method staticMethod() is also loaded into memory. These static members are associated with the class and are available for use without creating an instance of the class.
When an instance of upGradTutorials is created using the new keyword, memory is allocated to store the non-static variable nonStaticVariable within the instance. Each class instance has its own separate copy of the non-static variable.
In the main() method, we first access the static variable and call the static method using the class name. Since they are associated with the class, we can access them without creating an instance.
Next, we create an object obj of upGradTutorials and access the non-static variable and call the non-static method using the object reference obj. Non-static members are accessed through instances of the class.
Memory for the objects created using new is allocated on the heap, and when the objects are no longer referenced, they become eligible for garbage collection, and the Java runtime reclaims their memory. The static members persist throughout the execution of the program and are cleaned up when the program terminates.
A static nested class is a class that is defined within another class but marked with the static keyword. It is a nested class associated with the outer class itself rather than any specific instance of the outer class.
A static variable in Java provides a shared value across all instances of a class, allowing for storing data common to all objects. They offer a convenient way to access and manipulate shared information, enhancing code efficiency and reducing memory usage.
To learn more about static variables and their usage, you can sign up for a professional course offered by upGrad.
1. Can a static variable in Java be changed?
Yes, a static variable in Java can be changed by modifying its value directly or through methods that have access to the static variable.
2. Why do we need static variables in Java?
We need static variables in Java to store data shared among all class instances. It is a convenient way to access and manipulate common information.
3. What will happen if we do not use static variables in Java?
Not using static variables in Java will lead to unnecessary memory usage and potentially inconsistent or redundant data.
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
+918045604032
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.