Tuesday, 14 April 2015

​Static methods in Java

Static methods cause a lot of unnecessary confusion to programmers learning Java. Part of the problem is that static means different things in different programming languages. Here I explain what it means in Java…

Java program using static methods, shown in the NetBeans IDE
Usually, when you want to use a method provided by some class in Java, you have to create a new object based on that class. Then you can call the method from that object. So, for example, if you want to get the Northern exit of a Room object in a game you would first need to create a new Room object and then call an accessor method such as  getN()from that Room object like this:

Room goldRoom;
int exit;
goldRoom = new Room("room2", "Gold room", 0, 4, Direction.NOEXIT, 3)
exit = goldRoom.getN();

Sometimes, however, it may be useful call a method without having to create an object in order to do so. For example, let’s suppose you want to convert a string such as "200" to its integer representation 200. You could do that by first creating a new Integer object and then calling the valueOf() method with the string as an argument, like this:

Integer intOb;
int anInt;
intOb = new Integer(0);
anInt = intOb.valueOf(s);

This is pretty ugly and inefficient code, however. I have created an Integer object which I never really need simply in order to call the conversion method, valueOf()which is defined inside the Integer class. It would be much neater if I could just call valueOf() without having to create an Integer object first. Well, I can do that. Instead of creating an object from the Integer class, I just call valueOf() from the class itself, like this:


Let’s suppose a string variable s has the value "200" (in a real-world program this value might have been entered into a text field by the user or it might have been read from a file on disk). When I want use this value in a calculation I simply call Integer.valueOf(s) to return an integer value:

int x;
int total;
String s;
s = "200";
x = 5;      
total = x * Integer.valueOf(s);

Many other standard Java classes provide methods that can be called in this way. For example, the String class provides the format() method which lets you create a string by embedding values at points marked by ‘format specifiers’ (just like those used with the printf() function):

String.format("%d * %s = %d", x, s, total)

But you can’t just call any method in this way. In order to be called directly from the class rather than from an object, a method has to be declared as static. These are the declarations of the String.format() and Integer.valueOf() methods:

public static String format(String string, Object[] os)
public static Integer valueOf(String string)

Class methods & instance methods

You can think of static methods as being ‘class methods’ – they ‘belong’ to the class itself. This contrasts with other methods which you can think of an ‘instance methods’ – they ‘belong’ to instances of the class. An ‘instance’ of a class is an object created from the class ‘blueprint’.
If you want methods to be callable from your own classes, you need to add the keyword static to their declarations. Let’s take a look at a class that includes a static method.

Consider this method:

public static String numberOfObjects() {
        return "There are " + obcount + " objects.\n";

This displays a string that includes the value of the int variable obcount. You will see that this variable has been declared to be static and it has been initialized with a value of 0:

private static int obcount = 0;

static variable, like a static method, ‘belongs’ to the class rather than to individual objects created from that class. In my code, the MyObject constructor, which is called whenever a new object (a new ‘instance’ of the MyObject class) is created, adds 1 to the value of obcount.

obcount = obcount + 1;

Since a static variable belongs to the class, there is only ever one copy of that variable so it can only ever have one value, no matter how many objects based on that class have been created.
In the C language, the static keyword has a different effect. A static function is in C is private within the file in which it occurs. A static variable which is declared inside a function is one that retains its value between function calls.
The MyClass class also has an instance (non-static) variable, obnumber:

private int obnumber;

Each time a new object is created the constructor assigns the current value of obcount to this variable:

obnumber = obcount;

This means that each time a new object is created the static variable obcount is incremented and so it will be set to the total number of objects that have been created. There is only one copy of this static variable. So even if there are many objects, at any given moment this static variable will always have a single value. The instance variable obnumber is also incremented each time a new object is created. However, each object has its own copy of this instance variable so each object will have a different value for obnumber.

Let’s suppose you were to create three objects, ob1, ob2 and ob3. The obnumber of ob1 would be the original value of the variable (0) + 1; so for ob1, its value would be 1; for ob2 its value would be 2 and for ob3 its value would be 3. But the obcount variable, which belongs to the class rather than to any individual object, would be the same for all three objects – namely 3.

In brief then, instance variables store different values for each object. Static or ‘class’ variables store a single value which is accessible by all objects created from that class. Instance methods are called from an object but class methods are (usually) called from a class.

Learn Java - 73% Discount

This article is adapted from my eBook, The Little Book Of Java, which is provided with Java – The Master Course, a step-by-step interactive video tutorial to the Java language.

This is what you get with Java – The Master Course ….

  • 87 lectures and over 9 hours of content
  • All the source code ready-to-run
  • A 125-page eBook, The Little Book Of Java
  • Lifetime access to the course

The regular cost of this course is $149. But for a limited period, you can get the course for just $39. Just click this link: