Static is a Non Access Modifier in java. A static variables or methods belongs to a class rather than objects.
Static keyword in Java is used in the declaration of member methods, instance variables, inner classes and static blocks. However, static keyword is not applicable to a class. The static keyword in Java
is used mainly for memory management and to share common information among all objects of a class.
Static Variable
- Static variables are also known as class variables, they belongs to the class and not the instance if class(objects).
- Class variables also known as Static fields are shared by all objects of a class. Regardless of how many objects we create, there is only one instance of static variable for all objects. Same copy of a static field is accessed by all objects.
- Static variables are initialized(alocated memory) only once at the time of class loading. Static variables gets initialized before any object of that class gets created.
- To access a static variable we don't have to create an object. We can access a static variable by using the name of the class.
- Syntax to access static variables : <Class_Name>.<Static_Variable_Name>
- We can use static variables to define class level constants. If we want all objects to share a constant value like rate of interest, value of PI(3.141), Number of students in class etc, then we declare it as a class level constant using static keyword.
- Using static variables makes you program memory efficient as each object of class will share shame copy of static variables instead of creating it's own.
class BankAccount { // Static(Class) variables static String bankName = "CitiBank"; static int bankAccountCount = 0; // Instance variables int id; BankAccount(int accountId) { this.id = accountId; bankAccountCount++; } } public class StaticVariable { public static void main(String[] args) { BankAccount account1 = new BankAccount(100); printDetails(account1); BankAccount account2 = new BankAccount(101); printDetails(account2); } public static void printDetails(BankAccount account){ System.out.println("Id : " + account.id); System.out.println("Bank Name : " + BankAccount.bankName); System.out.println("Total Accounts : " + BankAccount.bankAccountCount + "\n"); } }Output
Id : 100 Bank Name : CitiBank Total Accounts : 1 Id : 101 Bank Name : CitiBank Total Accounts : 2
In the above program, we defined following three variables inside class BankAccount:
- bankName : A static string variable initialized with "CitiBank", whose value is shared among all objects of BankAccount. Only one copy of this variable is created.
- bankAccountCount : A static integer variable initialized with 0, whose value is shared among all objects of BankAccount. Only one copy of this variable is created.
- id : A instance variable(non-static) representing account Id of bank account. A new copy of Id variable is created for every object.
Inside printDetails method, we use object reference to access Id(instance variable) whereas we access static variables directly using class name.
Static Methods
- Like static variables, static methods also belongs to a class and not instances of class.
- A static method can only access static variables and can only call other static methods of class. It cannot access non-static variables and methods.
- A static method can be called without an object. Like static variables, we can invoke static methods using class name.
- We cannot use "super" and "this" reference inside static method as we can invoke it without any object.
We use static methods to write a common utility methods to be use by everyone. Static methods are heavily used in writing a shared library.
class Calculator { public static int addition(int a, int b) { return a + b; } public static int subtraction(int a, int b) { return a - b; } } public class StaticMethod { public static void main(String[] args) { int i = 20, j = 10; // Calling static methods int sum = Calculator.addition(i, j); int diff = Calculator.subtraction(i, j); System.out.println("i= " + i +",j= " + j); System.out.println("Sum: " + sum); System.out.println("Difference: " + diff); } }Output
i= 20,j= 10 Sum: 30 Difference: 10
In the above program, we defined two static methods "addition" and "subtraction" inside Calculator class. We can access these two methods without creating any object of Calculator class. Inside main method of StaticMethod class, we are calling addition and subtraction method using class name instead of using object reference.
Static Blocks
- Static block is a code block inside class body surrounded by { and } which gets executed once at the time of class loading. It gets executed even before main method.
- Static blocks are used to initialize static variables.
-
Syntax of static block
static { // static block statement }
class ClassOne { // static variable static int age; // static block static { age = 30; System.out.println("Inside Static Block"); } } public class StaticBlock { public static void main(String[] args) { System.out.println(ClassOne.age); System.out.println("Inside Main Method"); } }Output
Inside Static Block 30 Inside Main Method
In the above program, we created a static code block which initializes static variable "age" with value 30. As static blocks gets executed during class loading, the print statement inside static block gets executed before the main method of StaticBlock class.
Benefits of Static Variables and Methods
- Memory Efficiency : Static variables are allocated memory only once, regardless of the number of instances of the class. This can lead to more efficient memory usage, especially when the variable represents shared data or constants.
- Improved Code Readability : Static variables and methods can improve code readability by clearly indicating that a particular element is associated with the class itself rather than a specific instance.
- Centralized Utility : Static methods provide a way to create utility functions that are not tied to specific instances. They offer a centralized and organized way to group related functionality at the class level.
- Enhanced Performance : Since static methods and variables are associated with the class and not with instances, they can be accessed without the need to create an object. This can lead to improved performance in scenarios where instantiation is unnecessary.
Best Practices of Using Static Variables and Methods
- Use Static When Appropriate : Use static variables and methods when the behavior or data is associated with the class as a whole rather than with instances. This includes utility methods, constants, and shared data.
- Limit Global State : While static variables provide a form of global state, it's crucial to limit their use and be mindful of the impact on code maintainability and testability. Excessive use of global state can make the code harder to understand and maintain.
- Thread Safety : Ensure that static variables and methods are thread-safe, especially in a multithreaded environment. Synchronization mechanisms may be needed to prevent race conditions and ensure consistent behavior.
- Minimize Mutable Static State : Avoid mutable static state when possible. Mutable static variables can introduce concurrency issues and make code harder to reason about. If mutability is necessary, ensure proper synchronization mechanisms are in place.
- A static variable and static method can be accessed without using creating objects.
- static modifier cannot be applied to a class.
- A static method can only access other static variables and methods of a class.
- As static method cannot use super and this references.
- Static Methods can not be overriden.
Conclusion
Understanding and effectively using static variables and methods in Java is essential for writing efficient, organized, and maintainable code. By leveraging the class-level scope of static elements, developers can create utility functions, manage shared data, and enhance the overall structure of their programs. However, it's crucial to use static features judiciously, considering factors such as memory efficiency, code readability, and thread safety. Incorporating best practices when working with static variables and methods contributes to the creation of robust and scalable Java applications.