How to Use Java’s Static Keyword

Roger Winter

Published:

Have you ever wondered why the main function in a Java program contains the static keyword?

developer using the java static keyword in her work

The object-oriented nature of Java enables developers to plan classes and types of software using design patterns and the static keyword marks the fields and methods that are part of the class declaration.

The reason that the main function contains the static keyword is that it must be callable by the Java Virtual Machine (JVM) without having to instantiate anything from the package.Download Now: An Introduction to Java & JavaScript

In this post, we’ll discuss the Java static keyword and how it helps with the memory and lifecycle management of fields, methods, and classes. We’ll review static members (fields and methods) in the Java SDK, then demonstrate how to use the static keyword to create nested classes.

Static vs. Instance Methods in Java

By default, Java associates the fields and member methods to the instance of the class. The methods of the static scope do not require developers to an instance of the class.

Consequently, the static scope and the instance scope are separate. The instance scope, created when you create a new object, can access the instance fields, while the static scope can access only the static fields and methods.

Some design patterns — like the singleton pattern — use static. In a singleton pattern, you direct the JVM to allow only one instance of a type.

By default, classes hold instance-level scoped fields and methods. This means that the fields you create are bound to the lifetime of the instance of the type itself. For example, see the following code:

 
public Person {

        int id;

        String name;

}

The Person class holds two fields, id and name. You can create two instances of this type where each one can hold information that is specific to that instance:

 
Person one = new Person();

one.name = "John Doe";

Person two = new Person();

two.name = "Dohn Joe";

By default, these instances do not overwrite the values stored in the other variable. This is also known as instance-level scoping. The other type of scoping is static scope. You can also call static scope “class scope” because the class name accesses the fields and methods, not the instance name.

Take the following code as an example:

 
class Person {

         static int id;

         String name;

}

In the code above, the id field is a static member, not an instance member. To access this field, you use the class name, Person, rather than the name of the instance or the variable you create.

 
Person.id = 5;

System.out.println(Person.id);

The notable thing is that you can also access the static fields from the variables. So, the following code prints 5 twice:

 
Person one = new Person();

Person.id = 5;

System.out.println(Person.id);

System.out.println(one.id);

In the code above, you changed the static field once, and the type reflected the change. When the instance tries to access the values of a static member, it gets them from the class. Each class type does not isolate its static members.

So, a quick recap:

  • The instance members are specific to the instance where you create and assign them; the static members belong to the type itself.
  • You can access an instance member only from the instance variable, but you can access a static member from the type and the instance variables.
  • You can access a static field from the non-static or instance methods, but a static method cannot access the instance fields and members.

Static Fields & Methods in Java

In Java, you can apply the static keyword to modify the lifetime behavior of fields, methods, and classes. While you just learned about using the static keyword for fields in the section above, you can use them to make methods in a class static.

The static modifier can access the methods directly from the type name. Just apply the modifier in the method’s declaration to mark a method as static:

 
public static String sayHello() {

        // code here…

}

In the Java API, a lot of classes use static methods. For example, one of the most well-known and most-used String.format method is a static declaration that allows developers to format the output. You can format the output like this:

 
String template = "%s is %d years old";

String name = "John Doe";

int age = 35;

System.out.println(String.format(template, name, age));

In Java, you can also access the static methods from an instance variable. Accessing the static methods from an instance is not helpful because static methods cannot access the instance fields and members. Although you can access the format method on your String variables, you must pass the value again (because the format method cannot access the instance value).

See below:

 
String template = "%s is %d years old";

String name = "John Doe";

int age = 35;

System.out.println(template.format(template, name, age));

You can call the format method on the template variable, but the method cannot read the template value as that is in the instance scope, not the static or class scope. This becomes an anti-pattern where you create inconsistency between the code and the called methods. That is why it is always best to call the static methods on the type itself, not the instance.

On top of the static fields and methods, you can also use the static keyword to create static blocks. This makes Java a much more robust language enabling developers to create context on-demand.

But that’s not all that the Java static keyword can do. Nested static classes are another interesting feature that we’ll discuss next.

Constants & Nested Classes in Java

Java does not have a dedicated keyword to define constants, as we have in C-like programming languages. Java offers the final keyword that serves to make a field read-only or assign-once. When the program begins, you can assign a final variable using the constructor and retain the value throughout the program’s lifecycle.

The static keyword helps ensure that you initialize the member fields only once and apply them to the class scope.

You define a constant in Java as follows:

 
public static final String NAME = "THE_VALUE";

Note that the term static means you do not need to create an instance to access the values. Several APIs use this approach. For example, the Math library uses static keywords to expose values for PI, MAX_VALUE, and so on. The final keyword makes it once-assignable.

Another feature that the static keyword enables you to use is static classes. You can define classes within classes and access them using the parent class name.

 
class Person {

        static class Gamer {

           // code here…  

        }

}

In your main code, you can create the instance of a Gamer class like this:

 
Person.Gamer gamer = new Person.Gamer();

Note that you access the Gamer type from the Person type.

You should consider extending the Gamer type from the Person type to use the object-oriented approach for development instead of nested classes. But, this depends on your development needs.

How to Use the Static Keyword in Java

You can use the Java static keyword in a variety of web development scenarios, but one of the most common uses is in the main function of a Java program.

 
public static void main(String args[]) {

    // program code here

}

This defines a static context that the JVM can launch. Because the main function is static, the JVM does not need to create an instance of the class holding this method. But as a consequence, the main method cannot access any instance fields or members created within the same class.

Another area where you can use the static keyword is the singleton pattern. The singleton pattern ensures that the program creates only one class instance. The important things to note about a singleton pattern are:

  • It is a private constructor.
  • It is a static method used to access the instance.

 
public class EmailSender {

     private static EmailSender instance;

     private EmailSender() { }

     public static EmailSender getInstance() {

         if (instance == null) {

            instance = new EmailSender();

         }

         return instance;

     }

}

In your type, hide the constructor so other types cannot create an instance of the type. Then, create a static method that can be called without an instance of this type. The method can access the constructor, so you create a new instance and return it. Before returning, you save it in the type’s static field. The instance field and the getInstance method do not require creating an instance. Every time an instance is needed, outside types can use this method to get hold of the instance and use it, but they cannot create an instance by themselves.

Using the Static Keyword in Java Programming

In this article, you learned about the static keyword in Java and how it helps you improve application performance and code readability. The article highlighted the difference between the static and the default fields, also known as instance fields. Then, you learned how to create static fields in Java programs and how to use them. To control their lifecycle behavior, you can apply the static keyword to fields, methods, and class declarations.

You should now have a stronger understanding of how to use the static keyword to create constants, as Java does not have a const keyword like other C-like programming languages. The static keyword helps control the lifecycle of the fields and variables in a Java program.

In scenarios where creating an instance of a type yields less performance, such as with embedded devices, the static keyword can initialize throughout the program's lifetime. The static keyword helps you manage memory in a Java program and control memory management for fields and variables.java

 

Topics: Java

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about the differences between and uses of these popular programming languages.