Java Static Keyword

Josh - May 27 '21 - - Dev Community

What does the static keyword mean and how is it used. This keyword I have used many times but have only partially understood how it works under the hood. The primary characteristic of something that is static in Java is that it belongs to the class and not a specific instance. For regular variables and methods each time an object is instantiated a separate copy of each is created. Static variables are created once at the start of execution.

Now that we have learned what the static keyword is how is this useful in the context of an application? Reasons to use static is the value of the variable is independent and shared across each object. An example off the top of my head is if there was a total count variable that incremented each time an object is created. A static method that I use often is toString() from the integer class. This method does not required an integer object to be created and can be called directly from the class. Static methods and variables use dot notation to be referenced in the format class.variable or class.method().

Some other uses of the static keyword that I was not previously familiar with is the static block, class, and import. Starting with static blocks, they are used for initializing static objects. If a static array is created and elements need to be added then a static block acts almost as a constructor to populate that array at execution. In Java, classes are able to be nested which allows for the use of static classes. They will behave like normal classes but only the outer class will have access to it. A popular implementation is the Singleton model which often utilizes a static class to hold the instance. Lastly I will discuss the static import option. When the static keyword is used while importing a library the static members are available without using the class name. An example of this would be if a static import was called for the math library then the pow() method would be usable instead of Math.pow(). This makes sense for classes whose purpose is to provide methods that do not rely on objects or instances. Thank you for reading my post this week on the static keyword. Please leave a comment or like the post if you found it helpful.

Sources:

  1. Moock, C. (2007). Essential ActionScript 3.0: ActionScript 3.0 programming fundamentals. O'Reilly.

  2. Java Static Method, Variable and Block with Example. Guru99. (n.d.). https://www.guru99.com/java-static-variable-methods.html#:~:text=What%20is%20Static%20Variable%20in,the%20start%20of%20the%20execution.

  3. Baeldung. (2021, May 10). A Guide to the Static Keyword in Java. Baeldung. https://www.baeldung.com/java-static.

  4. Static import in Java. GeeksforGeeks. (2017, November 29). https://www.geeksforgeeks.org/static-import-java/.

. . . . . . . . . . . . . . . . . . . . .