For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
The static keyword in Java is a fundamental feature that allows developers to define class-level variables, methods, blocks, and nested classes. Unlike instance members, static members are shared across all objects of a class and can be accessed directly using the class name. This makes static an essential concept for memory management, code reusability, and implementing utility methods.
This blog provides a detailed guide to the static keyword in Java. We will cover its properties, practical applications, and advantages with real code examples. You’ll also learn about static variables, methods, blocks, and nested classes, along with best practices and common interview questions. By the end, you’ll have a clear understanding of how and when to use static in Java effectively.
Advance your Java programming expertise with our Software Engineering courses and elevate your learning to the next level!
As a beginner, you may wonder why we use static keyword in Java. The main reason is that it helps save memory. Java’s static keyword possesses distinct characteristics that set it apart, and they are mentioned below.
Accelerate your tech career by mastering future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Gain hands-on experience, learn from industry leaders, and develop the expertise that top employers demand.
1. Class Association: Static members can be accessed by using the class name because they are linked to the class. This suggests that modifications to one are applied to all instances of the class and that the class name can be used to access static members rather than an object reference.
2. Lifetime: Static members are present from the point at which the class is loaded into memory to the instance at which the program ends.
3. Direct Access: Static members can be accessed directly without the need to construct a class object, making them easily usable. Thanks to this feature, they can then offer constants and useful functions that can be utilized throughout the program.
4. Shared memory allocation: During program execution, memory is only allocated once for static variables and methods. Since all instances of a class share this memory space, static members are necessary for maintaining the global state or shared functionality.
5. Accessibility: The availability of non-static members is restricted because static methods and variables are not connected to a particular instance of the class.
6. Static methods can be overloaded, allowing the development of many methods with the same name but different parameters. These cannot be overridden because they are associated with the class rather than a specific instance of the class.
A member can be accessed without referencing an object and before any objects of its class are created if it is declared static. In the following Java code, for instance, the static method m1() is obtained without creating an instance of the Test class.
// Java program to demonstrate that a static member
// can be accessed before instantiating a class
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
public static void main(String[] args)
{
// calling m1 without creating
// any object of class Test
m1();
}
}
Output
from m1
Static blocks are utilized to initialize static variables or perform other static operations. They are executed when the class is loaded into memory, even before the creation of any objects. They are enclosed within a pair of curly braces and preceded by the static keyword. Further, the static keyword is used when one needs to perform one-time initialization. Here's an example:
java
public class MyClass {
static {
System.out.println("Static block executed!");
}
public static void main(String[] args) {
System.out.println("Inside the main method");
}
}
Output:
scss
Static block executed!
Inside the main method
Static variables, also known as class variables, are shared among all instances of a class. They retain their values throughout the execution of the program. Here's an example:
java
public class MyClass {
static int count = 0;
public MyClass() {
count++;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println("Count: " + count);
}
}
Output:
makefile
Count: 2
Static methods in Java belong to the class itself and can be invoked directly without creating an object. They are commonly used for utility functions or operations that don't require instance-specific data. Here's an example:
java
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = MathUtils.add(5, 3);
System.out.println("Result: " + result);
}
}
Output:
makefile
Result: 8
Static variables and methods are suitable in various scenarios. Let’s study the use of static variables and static methods in Java with examples.
1. Utility Methods: When a method doesn't rely on any instance-specific data, it can be made static for easy access. For example, consider a MathUtils class that provides mathematical operations:
java
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 3);
int product = MathUtils.multiply(2, 4);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}
Output:
makefile
Sum: 8
Product: 8
In this example, the add method is called with arguments 5 and 3, and the multiply method is called with arguments 2 and 4. The returned values are then printed to the console, resulting in the output shown above.
You can access these static methods directly using the class name, such as MathUtils.add(5, 3) or MathUtils.multiply(2, 4).
2. Counters: Static variables are useful for counting the number of instances created for a class. Let's say you have a Car class, and you want to keep track of the total number of cars created:
public class Car {
private static int totalCars = 0;
public Car() {
totalCars++;
}
public static int getTotalCars() {
return totalCars;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
System.out.println("Total cars created: " + Car.getTotalCars());
}
}
Output:
mathematica
Total cars created: 3
The totalCars variable is static and increments each time a new Car object is created.
3. Constants: Static variables can be used to store constants that remain the same across all instances. Let us consider a class representing the mathematical constant pi:
java
public class MathConstants {
public static final double PI = 3.14159;
public static final double E = 2.71828;
// Other constants...
}
Using the class name MathConstants.PI or MathConstants.E, these ultimate static variables are accessible anywhere in the program.
By utilizing static variables and methods in these circumstances, you can improve Java program code organization, efficiency, and reusability.
Java allows the creation of static nested classes, which are declared as static within another class. These classes can access only the static members of the enclosing class. Here's an example:
java
public class OuterClass {
static class NestedClass {
void display() {
System.out.println("Nested class display");
}
}
public static void main(String[] args) {
OuterClass.NestedClass nestedObj = new OuterClass.NestedClass();
nestedObj.display();
}
}
Output:
kotlin
Nested class display
The output "Nested class display" is generated because the `display()` method of the `NestedClass, nested within the `OuterClass, is invoked through an instance of the nested class.
The static keyword offers several advantages:
1. Memory Efficacy: You can store static members in a single location in memory, reducing memory consumption.
2. Convenient Access: Static members can be accessed directly using the class name without the need for object creation.
3. Code Reusability: Static methods and variables allow for code reuse across multiple instances of a class.
4. Static members can be accessed more swiftly and effectively than their non-static counterparts because they are associated with the class rather than with individual instances.
5. Utility methods that don't need access to an object's state can be contained in static methods. This can improve the organization of the code and make it easier for utility methods to be reused across different classes.
6. Constants: Static final variables can be used to define program-wide constants.
7. Static methods can be used to implement class-level functionality, such as factory methods and utility functions that don't need access to an object's state.
Before concluding this Static keyword in Java tutorial, investigating static blocks and classes, let's discuss a few distinctions between static and non-static variables and methods in Java.
Static Variables | Non-static Variables |
They can be accessed using the class names | Objects can be accessed using non-static variables. |
They can be accessed using either static or non-static methods | Accessing them is restricted to non-static methods. |
They only receive a single memory allocation when the class is launched | Each object is allocated its own memory. |
All instances or objects of the class share the same variables | The non-static variables are duplicated for each object. |
The scope of static variables is global | The scope of non-static variables is local. |
Static Method | Non-static Method |
These methods support early or compilation-time binding. | They may facilitate runtime, dynamic, or late binding. |
These methods can only access the static variables of their own class and other classes. | They have access to both static and dynamic members. |
No static method overrides are allowed. | They can be bypassed. |
Since only a single memory allocation is performed when the class is launched, less memory is consumed | Each object has its own memory allocation. |
The static keyword in Java is essential for creating class-level variables, methods, blocks, and nested classes that are shared across all instances. It enhances code reusability, optimizes memory usage, and simplifies access to class-level members.
While static members cannot directly access non-static variables and static methods cannot be overridden, understanding these limitations allows effective handling of non-static data. Mastery of the static keyword ensures efficient Java programming, improves code organization, and boosts performance, making it a vital tool for developers aiming to write clean, maintainable, and high-performing Java applications.
The static keyword in Java defines class-level members accessible by all instances, whereas final is used to declare constants or prevent modification of variables, methods, or classes. Static members can change values (if not final), while final ensures immutability. Both are essential for managing memory and behavior in Java programs.
The main method in Java serves as the entry point of a program. Declaring it static allows the JVM to call it without creating an instance of the class. This ensures the program starts correctly and executes as intended, demonstrating one of the most common uses of the static keyword in Java.
Static variables in Java are not inherently thread-safe. Since they are shared across all class instances, concurrent access by multiple threads can cause race conditions or data inconsistencies. Proper synchronization techniques, such as synchronized blocks or atomic classes, are required to safely manage static variables in multithreaded applications.
No, static methods cannot directly access non-static variables because they belong to the class, not an instance. To use non-static variables in static methods, you must pass an object reference or employ other techniques. Understanding this limitation is essential for proper usage of the static keyword in Java.
Static members are allocated in a single memory location when the class is loaded, rather than per object. This reduces memory consumption and improves performance for shared resources. Static keyword in Java ensures that class-level variables and methods are consistent and accessible across all instances without duplicating memory.
Static blocks are executed when a class is loaded and are used to initialize static variables or perform one-time setup tasks. They are ideal for configuring constants, logging, or establishing database connections. Static keyword in Java allows these blocks to execute before any objects are created.
Yes, static methods can be overloaded in Java by creating multiple methods with the same name but different parameter lists. This allows flexibility while retaining class-level accessibility. Overloading static methods helps organize utility functions and enhances code reusability in Java programs.
Static methods are associated with the class itself, not an instance, and are resolved at compile time. This prevents them from being overridden, unlike instance methods. Understanding this limitation is critical for correctly using the static keyword in Java, especially when designing polymorphic or inheritance-based structures.
Static nested classes do not hold a reference to their outer class and can only access static members. Inner classes, on the other hand, maintain a reference to the enclosing class and can access both static and non-static members. Using static keyword in Java for nested classes improves memory efficiency.
Static keyword in Java improves memory efficiency, enables class-level constants, allows direct access without object creation, and promotes code reusability. It helps create utility methods, shared counters, and class-wide settings, making it a critical feature for optimizing Java programs and improving performance across multiple objects.
Static variables belong to the class and are shared across all instances, while instance variables are unique to each object. Changes to a static variable affect all objects, whereas instance variables maintain separate values. This distinction is crucial when applying the static keyword in Java to manage memory and shared resources.
Yes, static variables in Java are automatically initialized when the class is loaded. Numeric types default to 0, booleans to false, and object references to null. This automatic initialization ensures predictable behavior and reliability when using the static keyword in Java for class-level data.
By declaring a variable as static final, you create class-wide constants. These are initialized once, cannot be modified, and are shared across all instances. This provides consistent values, reduces memory usage, and ensures reliability, demonstrating a common and effective use of the static keyword in Java.
Yes, static methods can call other static methods directly using either the method name or class name. This is possible because static methods belong to the class, not instances. Leveraging this allows developers to organize utility functions efficiently and maximize the advantages of the static keyword in Java.
Static variables are shared across all objects of a class, making them ideal for tracking global information like counters or configuration settings. This shared access ensures consistency and centralization, highlighting the importance of the static keyword in Java for class-level state management.
Yes, but it’s not recommended. Static members are tied to the class, not an object, so accessing them via object references can be confusing. Using the class name to access static members is clearer, safer, and reflects best practices when employing the static keyword in Java.
Static members are shared across all instances, so in multithreaded environments, concurrent access can cause race conditions. Proper synchronization mechanisms, like synchronized blocks, locks, or atomic classes, are needed to maintain thread safety when using the static keyword in Java.
Static methods belong to the class and cannot access instance variables directly, whereas non-static methods belong to objects and can access both static and non-static members. Understanding this distinction is essential for correct usage of the static keyword in Java and designing efficient class structures.
Static methods are resolved at compile time and cannot participate in runtime polymorphism. Unlike instance methods, they cannot be overridden, limiting flexibility in inheritance hierarchies. This is a key limitation of the static keyword in Java that developers must consider when designing object-oriented systems.
Yes, from Java 8 onward, interfaces can have static methods. These methods are associated with the interface itself, cannot be overridden, and can provide utility functions. This extends the functionality of interfaces while leveraging the static keyword in Java for shared class-level behavior.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free
Author|900 articles published