Warning: Constant FORCE_SSL_ADMIN already defined in /home/danieltzy/public_html/dblg001/wp-config.php on line 94
Static Keyword in Java - What in the world is it? - Daniel's Blog

Static Keyword in Java – What in the world is it?

Is a question many young and naive Java developers have that often go unanswered due to overly-complicated explanations that are rather obscure, and not geared towards beginners.

Here(not just this article/post but on the behalf of any subsequent tutorials), I aim to provide a quick yet effective definition of what this keyword actually means, and what it can be used for.

A Quick Definition

The static keyword tells Java that a method or variable in a class should be made accessible without the need of instantiation. Therefore, it’s a part of the class itself, rather than an attribute that you should be able to modify for each object you create.

Example - How can I use it?

Let’s create an application that categorises users into their age groups, based on their age input. These age groups consist of seniors, middle-aged, and youngsters. 

Let’s start by creating a class for each of them, and group them into a package just for demographics.

package org.demographics;

public class Senior/MiddleAged/Young {
public static int ageGroup = ??;
...some more code dedicated to each class...
}

Now, let’s create the main class that will make use of these classes and make up the logic of the application itself.

// Main class where we specify the logic
import org.demographics.Senior;
import org.demographics.MiddleAged;
import org.demographics.Young;

public class Categoriser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your age");

int age = scanner.nextInt();
String ageGroup = "";

if (age >= Senior.ageGroup) {
ageGroup = "Senior";
…do stuff, instantiate Senior and add to an array, etc…}

else if (age >= MiddleAged.ageGroup) {
ageGroup = "Middle Aged";
…do more stuff…
}

else if (age >= Young.ageGroup) {
ageGroup = "Young";
…do more stuff…
}

else {
System.out.println("You are too young!");
return;
}

System.out.println("You shall be categorised as " + ageGroup);
}
}

Reminder

Remember, we made the ageGroup variable static because:

1. We want to be able to access it without or before instantiation, otherwise we’d have to do: 

Senior placeholderSenior = Senior();
int seniorAgeGroup = placeholderSenior.ageGroup;

2. It is clearly established for all objects created from that class, and can’t be modified for any exceptional object. We don’t want two Senior objects having an age group of 10 years old and the other 60 years old.

Note

Do note that static variables aren’t constant(some may misunderstand it to be), rather it is consistent across all its instantiated objects. It can be changed, but the change will be reflected across all objects instantiated from it.