last modified July 15, 2024
In this article we cover the static keyword in Java. We coverstatic variables, methods, nested classes, blocks, and imports.
DefinitionThe static keyword is a non-access modifier. The type that hasstatic modifier does not belong to the instance of a class; itbelongs to the class. In addition to this, static can be usedto create class initializers, constants, and have imports of static variableswithout class qualification.
Usage of static keywordThe static keyword can be applied to:
variablesmethodsblocksnested classesimportsJava static variableStatic variables are also known as class variables. All instances of a classshare the same copy of a static variable. They are initialized only once, atthe start of the execution. A class variable can be accessed directly by theclass name, without the need to create a instance. One common use ofstatic is to create a constant value that is attached to a class.
Static variable exampleMain.javaimport java.util.ArrayList;import java.util.List;class Being {public static int count;}class Cat extends Being {public Cat() {count++;}}class Dog extends Being {public Dog() {count++;}}class Donkey extends Being {public Donkey() {count++;}}void main(String[] args) {List beings = new ArrayList();beings.add(new Cat());beings.add(new Cat());beings.add(new Cat());beings.add(new Dog());beings.add(new Donkey());int nOfBeings = Being.count;System.out.format("There are %d beings %n", nOfBeings);}In the code example, we keep track of beings created with a static variable.
class Being {public static int count;}A static variable is defined. The variable belongs to the Beingclass and is shared by all instances of Being, includingdescendants.
class Cat extends Being {public Cat() {count++;}}The Cat class inherits from Being. It increments thecount variable.
class Dog extends Being {public Dog() {count++;}}The Dog class increments the same class variable. So Dogand Cat refer to the same class variable.
int nOfBeings = Being.count;We get the number of all beings created. We refer to the class variableby its class name followed by the dot operator and the variable name.
Java static variable propertiesStatic variables have default values.Static variables can be accessed directly in static and non-static methods.Static variables are called class variables or static fields.Static variables are associated with the class, rather than with any object.Java static methodStatic methods are called without an instance of the object. To call a staticmethod, we use the name of the class, the dot operator, and the name of themethod. Static methods can only work with static variables. Static methods areoften used to represent data or calculations that do not change in response toobject state. For instance, java.lang.Math contains static methodsfor various calculations.
We use the static keyword to declare a static method. When nostatic modifier is present, the method is said to be an instancemethod.
Static method restrictionsStatic method can only call other static methods. They can only access staticdata and cannot refer to this and super.
Static method examplecom/zetcode/Main.javapackage com.zetcode;class Basic {static int id = 2321;public static void showInfo() {System.out.println("This is Basic class");System.out.format("The Id is: %d%n", id);}}public class Main {public static void main(String[] args) {Basic.showInfo();}}In our code example, we define a static ShowInfo method.
static int id = 2321;A static method can only work with static variables. Static variables arenot available to instance methods.
public static void showInfo() {System.out.println("This is Basic class");System.out.format("The Id is: %d%n", id);}This is our static ShowInfo method. It works with astatic id member.
Basic.showInfo();To invoke a static method, we do not need an object instance.We call the method by using the name of the class and the dotoperator.
The static main methodIn Java console and GUI applications, the entry point has the followingsingnature:
public static void main(String[] args)By declaring the main method static, it can be invokedby the runtime engine without having to create an instance of the main class. Since theprimary reason of main is to bootstrap the application, there is noneed to have an instance of the main class.
In addition, if the main method was not static,it would require additional contracts such as a default constructor or a requirementof the main class not to be abstract. So having a static mainmethod is a less complex solution.
Java static blockA code block with the static modifier is called a class initializer. Acode block without the static modifier is an instance initializer. Classinitializers are executed in the order they are defined, top down, when theclass is loaded.
A static block executes once in the life cycle of any program, and there is noother way to invoke it.
Static block exampleMain.javapackage com.zetcode;public class Main {private static final int i;static {System.out.println("Class initializer called");i = 6;}public static void main(String[] args) {System.out.println(i);}}This is an example of a static initializer.
static {System.out.println("Class initializer called");i = 6;}In the static initializer, we print a message to the console and initialize astatic variable.
Static nested classesA static nested class is a nested class that can be created without the instanceof the enclosing class. It has access to the static variables and methods of theenclosing class.
Static nested classes can logically group classes that are only used in oneplace. They increase encapsulation and provide more readable and maintainablecode.
Static nested classes restrictionsStatic nested classes cannot invoke non-static methods or accessnon-static fields of an instance of the enclosing class.
Static nested class exampleMain.javapackage com.zetcode;public class Main {private static int x = 5;static class Nested {@Overridepublic String toString() {return "This is a static nested class; x:" + x;}}public static void main(String[] args) {Main.Nested sn = new Main.Nested();System.out.println(sn);}}The example presents a static nested class.
private static int x = 5;This is a private static variable of the JavaStaticNestedClassclass. It can be accessed by a static nested class.
static class Nested {@Overridepublic String toString() {return "This is a static nested class; x:" + x;}}A static nested class is defined. It has one method which prints a messageand refers to the static x variable.
Main.Nested sn = new Main.Nested();The dot operator is used to refer to the nested class.
Java static importStatic imports allow members (fields and methods) defined in a class aspublic static to be used in Java code without specifying the classin which the field is defined.
Static import disadvantagesThe overuse the static import feature can make our program unreadable andunmaintainable, polluting its namespace with all the static members we import.
Static import exampleMain.javapackage com.zetcode;import static java.lang.Math.PI;public class Main {public static void main(String[] args) {System.out.println(PI);}}In the example, we use the PI constant without its class.
Java constantsThe static modifier, in combination with the finalmodifier, is also used to define constants. The final modifierindicates that the value of this field cannot change.
public static final double PI = 3.14159265358979323846;For example, in java.lang.Math we have a constant namedPI, whose value is an approximation of pi (the ratio of thecircumference of a circle to its diameter).
Singleton patternSingleton design pattern ensures that one and only one object of a particularclass is ever constructed during the lifetime of the application.
Singleton.javapublic class Singleton {private static final Singleton INSTANCE = new Singleton();private Singleton() {}public static Singleton getInstance() {return INSTANCE;}}In this simple code excerpt, we have an internal static reference to the singleallowed object instance. We access the object via a static method.
SourceJava tutorial
In this article we have presented the Java static keyword.
AuthorMy name is Jan Bodnar and I am a passionate programmer with many years ofprogramming experience. I have been writing programming articles since 2007. Sofar, I have written over 1400 articles and 8 e-books. I have over eight years ofexperience in teaching programming.
List all Java tutorials.