JEFF Media Developer Blog

Java & Spigot development

Menu
  • Blog
  • Main Website
  • Privacy Policy
Menu

Static Methods and Fields: When to use them and when to avoid them

Posted on August 8, 2021December 17, 2021 by mfnalex

Many people are going crazy whenever they see the static keywoard inside some source code. That’s ridiculous, because it alleges the people who developed Java were totally stupid.

It is true that the static keyword gets abused by many people, but there’s a difference between static abuse and proper use of the keywoard.

What does static mean?

To explain, I have to assume that you already know basic Java concepts.

As you know, Objects can have different fields and methods. For example, look at this class:

public class Person {
    private final String name;
    private final int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

This class can be used to create as many persons as you want. Every person has their own name and age, which is why those fields are NOT declared as static. Both name and age are so-called instance variables, meaning they can be changed per object instance.

Utility classes

However, sometimes you write classes that do not depend on their own instances. A good example for that are Utility classes, that do not need any instance variables.

Let’s assume you frequently need to convert Location objects into a nice formatted String, something like this:

X: 125, Y: 64, Z: -455 (world_nether)

You can easily achieve this by writing a class that looks like this:

public class Utils {
	public String locationToString(Location location) {
		int x = location.getBlockX();
		int y = location.getBlockY();
		int z = location.getBlockZ();
		String world = location.getWorld().getName();
		return String.format("X: %d, Y: %d, Z: %d (%s)",x,y,z,world)
	}
}

This method is working totally fine, but it requires an instance of the Utils class. However, this method does not use any instance variables at all, which means we can simply declare it as static without problems.

If we do not declare the method as static, we would have to use this code to call it:

new Utils().locationToString(myLocation);

If we would simply add the static keyword to the locationToString method, no instance creation is needed to call it, which means that the JVM doesn’t have to create a new object everytime, allocate RAM for it and also doesn’t have to check whether references to this object exist everytime the Garbage Collector runs:

Utils.locationToString(myLocation);

Static fields

You can also declare some fields as static. You can do so when the field describes something about the class itself, that’s not related to the instance. For example, lets imagine you made a Person class and you assume that no person can ever reach an age above 150 years:

public class Person {

	private final static int MAX_AGE = 150;

	private final String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		if (age <= MAX_AGE) {
			this.age = age;
		} else {
			throw new IllegalArgumentException("No one can be older than 150 years!");
		}
	}

	public void setAge(int age) {
		if (age <= MAX_AGE) {
			this.age = age;
		} else {
			throw new IllegalArgumentException("No one can be older than 150 years!");
		}
	}

}

Singleton classes

Sometimes you have a class that will never have to be instantiated more than once. For example, let’s assume you have some PlayerManager class. You could of course instantiate it in your main class and retrieve it whenever you need it, but – why? Since you KNOW that you never need more than one instance of it, you can easily declare all its fields and methods to be static.

TL;DR

You can declare everything as static that either describes stuff about the class itself, or that will never be changed in any object instances.

Join my Discord Server for feedback or support. Just check out the channel #programming-help 🙂

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • Solution: Creating a Datastore on Proxmox Backup Server fails at “Chunkstore create” (“File exists” or “Too many links”)
  • Don’t disable dependency-reduced-pom.xml
  • Maven Multi-Module setup for supporting different NMS versions
  • How to read or block Spigot’s console output
  • Why IntelliJ complains about your pom.xml file

Recent Comments

  1. mfnalex on Creating custom heads in Spigot 1.18.1+
  2. Timon Coucke on Maven Multi-Module setup for supporting different NMS versions
  3. 3ricL on Creating custom heads in Spigot 1.18.1+
  4. Ryan Leach on Why the GPL does NOT directly apply to all Spigot plugins
  5. Azzy on NMS: Use Mojang maps for your Spigot plugins with Maven or Gradle

Archives

  • December 2024
  • August 2023
  • July 2023
  • June 2023
  • February 2023
  • January 2023
  • October 2022
  • August 2022
  • March 2022
  • December 2021
  • October 2021
  • August 2021
©2025 JEFF Media Developer Blog
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT