1. Introduction
Java static keyword is excellent for conserving the application’s memory – no matter how many objects come alive, it ensures that any given element will only ever exist once. But why do we even need to use static? In this article, we will delve into the static keyword in Java.
2. Understanding the Static Keyword
In Java, the static keyword means that an element is associated with a class instead of an individual instance of that class. This signifies there will only ever be one version of the given static member, which all other instances can access.
3. Static Class Variable
As static variables are associated with a class, we can access them directly by naming the class. Every time we instantiate a class, there will always be only one copy of its static variable. This particular value is common to all objects from the same class, regardless of how often it has been initialized.
Additionally, static variables must only be declared at the class level, and there is no need for an object instance to invoke them.
It is possible to access static variables using an object reference; however, this should be avoided as it can become complicated to determine if the field in question is a class or instance. Therefore, always refer to static variables by their respective class name for clarity.
@Data @AllArgsConstructor public class User { public static int userCount = 0; private String name; private String age; public User(String name, int age) { this.name = name; this.age = age; userCount += 1; } }
So we have this User class with three attributes with the static variable counter. There is no need to waste memory and hold a counter per User instance since we are counting objects of the User class, so it makes perfect sense to do it using a static variable approach.
The static variable is available globally and can be accessed by other application resources. It’s vital to remember that the static variable belongs to the class, not the instance.
4. Nested Static Class
Java allows us to create nested classes to organize smaller, exclusive elements for a particular place. This aids in simplifying our code and making it more understandable.
When using nested classes together, we indicate using them solely in a single location while facilitating encapsulation and making the code more understandable.
If a nested class doesn’t demand access to any of its enclosing instance members, then we should declare it as static; doing so decouples the outer class from this inner one while also optimizing memory usage since no heap or stack will be necessary.
The static inner class won’t prevent garbage collection, whereas the inner class will due to its current active reference. Let’s take a look at this example:
public class App { private String element; public static void main(String[] args) { NestedApp app = new App.NestedApp(); } public static class NestedApp { } }
We have created a static nested class inside the top-level App class. The NestedApp class cannot access the String variable element of the App class unless it’s referenced via the App instance itself. It’s because static members cannot access non-static content.
4.1 As Singleton Pattern
public class DBConnection { private DBConnection() {} private static class DBConnectionInstance { public static final DBConnection instance = new DBConnection(); } public static DBConnection getDBConnectionInstance() { return DBConnectionInstance.instance; } }
The compelling usage of a static nested class is to enforce a singleton pattern. Singletons are handy when you only want a single class instance. DBConnection is a good candidate in this example since you usually only need to define database settings once.
The instance in the above example will only exist once because we have defined a private constructor to prevent instantiation while expositing a single instance using the static method.
Due to their serialisation defence, you may want to consider enumerations for singleton pattern design.
5. A Static Method
Typically, static methods are utilised to implement operations that don’t require the creation of any instances.
The code inside the Java static method is similar to a static variable. It will be shared across instances of a given class. A static method is a perfect candidate for utility classes since those share functionality across the application. Here is an example of a static method:
public static void printUserCount() { System.out.println("Count user globally " + User.userCount); }
Aside from being available globally, the static method improves performance since we don’t need to create a new instance during invocation.
There are also several constraints regarding static methods that are important to be aware of.
- A static method cannot be abstract, and you cannot use super or this keyword.
- Java resolves static methods at compile time, and static methods can’t be overridden because method overriding is part of runtime polymorphism.
- Unlike instance methods, static methods cannot access an object’s specific variables and method directly; they must be given a reference to that particular object.
- Static methods can access other static content, such as static methods or static variables.
6. The Static Block
To initiate static variables, a static block is necessary. As initializing these variables during declaration can often be too limiting for more complex cases that require multiple lines of code, this approach works best when further processing is required. Thus, using a static block proves valuable in situations like these.
Static Block Initializer is executed when the class is loaded. A class can have multiple static blocks and will be executed in the order they appear in the class.
public class App { private static Map<Integer, String> staticElements; static { staticElements = new HashMap<>(); staticElements.put(1, "One"); staticElements.put(2, "Two"); staticElements.put(3, "Three"); } }
An example is a utility class with a hashMap lookup with elements shared across the application. We need to use a static block initialiser to add elements to the static map.
Utilizing static blocks is a wise decision, especially If the initialization of static variables requires more than just the assignment but extra logic or if you need to provide exception handling in case of any errors.
7. Summary
The static keyword in Java is truly remarkable – an uncreated, unchanging utility of global proportions ready to feed your programming needs! Not only does it help you with memorization savings (no object instantiation needed!), but these classes also allow us access from anywhere.
Daniel Barczak
Daniel Barczak is a software developer with a solid 9-year track record in the industry. Outside the office, Daniel is passionate about home automation. He dedicates his free time to tinkering with the latest smart home technologies and engaging in DIY projects that enhance and automate the functionality of living spaces, reflecting his enthusiasm and passion for smart home solutions.
Leave a Reply