What do you mean by static in Java?

When I was learning Java, I always get confused what static variables and static methods mean. I read a lot of books explaining static and still it’s not clear to me. Let’s consider the “Hello World” class and program in Java.

// HelloWorld.java
public class HelloWorld {
	public static void main (String args[]) {
		System.out.println ("Hello World!");
	}
}

and consider the following class,

// HelloWorld.java
public class HelloWorld {
	public void main (String args[]) {
		System.out.println ("Hello World!");
	}
}

Are these two classes the same?  Of course, they are not the same. The first class has a static keyword in its main method and the other one is simply a method without this keyword static.As always Java follows this signature in the first class. And we consider this as a complete and a running program in Java. The static main method means that all objects created out from this class has only one method main. And you can call main method without instantiating the class and directly invoke this method with the name of the class (HelloWorld.main()).All instance variables and methods of the class that are declared as static are global variables or global methods. And we can call them directly without creating an object from a class by putting it’s class name in front of a variable and a method name in between the dot operator.Let’s consider a class counter example. We define a class, Song, and define the global variable count that increments every time we create an instance of the class, Song.

// Song.java
public class Song {
	private String title;
	// global variable
	public static int count;

	public Song (String title) {
		this.title = title;
		// Increment class variable count every time song is created.
		Song.count++;
	}

	public String toString () {
		return title;
	}
}

// SongDriver.java
public class SongDriver {
	public static void main (String args[]) {
		Song hello = new Song ("Hello");
		System.out.print ("Song " + Song.count + ": ");
		System.out.println (hello);
		Song elMundo = new Song ("El Mundo");
		System.out.print ("Song " + Song.count + ": ");
		System.out.println (elMundo);
	}
}

The program simply increments count when the hello object is created. And it increments again when elMundo is created. And we display the value of count by invoking count with it’s class name, Song.count.Therefore, when we say static, it is global and we can also call them class variable or class methods.

Leave a comment