Java static methods and variables

All the Instance variables belong to the objects that are created. In many cases, variable could belong to the class and not any objects such as how many times a specific class has been instantiated. That kind of information could not be provided by objects, because every object knows only about it self and not the history of its class. For that kind of information we need static members.

 

What is a static member (variable, method)  in Java?

A static member of a class could be a variable or a method and it belongs only to the class unlike instance members which belong to the objects. An example is counting the number of  instances of a class. A static member in Java can be declared by using the keyword static as shown in the example below.

static-members-color

Example

In this example two integer variables are declared. The first one is an instance variable (count) and the second one is a static variable (stCount). Each time you create an object the constructor adds one to the instance variable as well as the static variable. We want to see the result whether those two variables track the number of the objects that are created.

 

In the TestCounter class we have created 6 objects. The question is whether the sixth object has any information about the number of the objects that have been created before.

When the following program is compiled and run, the static variable (stCount) becomes 6, because it belongs to the class. The instance variable has no idea about the number of the objects that have been created.

Question: What happens when the following program is compiled and run?

 

public class Counter {

	int count;
	static int stCount;

	public Counter() {
		count ++ ;
		stCount ++ ;
	}
	public int getCount(){
		return count;
	}
	public static int getStCount(){
		return stCount;
	}
}

public class TestCounter {

	public static void main(String[] args){
		Counter cs1 = new Counter();
		Counter cs2 = new Counter();
		Counter cs3 = new Counter();
		Counter cs4 = new Counter();
		Counter cs5 = new Counter();
		Counter cs6 = new Counter();
		System.out.println("count is: " + cs6.getCount());
		System.out.println("stCount is: " + cs6.getStCount());
	}
}

 

Answer:

count is: 1
stCount is: 6, because the static variable tracks all the six objects that have been created.

Question:

We used the sixth object to return the total numbers of the objects that have been instantiated. What would happen if you use the first object instead of the sixth one?

System.out.println("count is: "+cs1.getCount());
System.out.println("stCount is: "+cs1.getStCount());

 

Answer:

That doesn’t matter, because the static variable belongs to the class not to any objects. The answer is the same.

 

Creating objects to access static members is redundant

The above example showed that creating objects to access static members of a class is redundant. The question is why would we need to create objects at all for static members.

It is actually unnecessary, and the solution in Java is that you can access all the static members of any class by using the name of the class as shown below:

In the previous example we can use the name of the class to access the static method getStCount().

System.out.println("count is: "+cs1.getCount());
System.out.println("stCount is: "+Counter.getStCount());

 

How to prevent instantiation of a class with only static members?

It is unnecessary to instantiate classes that have only static variables and methods such as the Math class in the standard Java API. To prevent instantiating such a class you need to define its constructor private.

 

Exercise

1- What is written to the standard output as the result of executing the following statements?

2- Is it necessary to instantiate the class Calculus? clarify your answer.

3- How can you prevent anyone to instantiate the class Calculus?

4- If you prevent instantiating the class Calculus, how can you access the method getSum?

public class Calculus {

	public static double getSum(double d1, double d2){
		return d1 + d2;
	}
}

public class TestCalculus {

	public static void main(String[] args){
		Calculus cal = new Calculus();
		Calculus cal2 = new Calculus();
		Calculus cal3 = new Calculus();
		System.out.println(cal.getSum(59,78));
		System.out.println(cal2.getSum(59,78));
		System.out.println(cal3.getSum(59,78));
	}
}

Answer of the exercise

  • 1- all the three different objects will return the same result which is: 137.0, 137.0, 137.0
  • 2- it is not necessary to instantiate the class Calculus, because it has only one static method. That is why all the objects return the same result. Static members belongs to the class not to any object.
  • 3- you can prevent instantiating the class Calculus by defining its constructor private as shown below.
  • 4- You can access the method getSum by using the class name without creating objects as shown below. The following code writes also 137.0 to the standard output. That is why instantiating this class doesn’t make sense.

 

public class Calculus {

	private Calculus() { // Calculus constructor is private
	}
	public static double getSum(double d1, double d2){
		return d1 + d2;
	}
}

public class TestCalculus {

	public static void main(String[] args){
		System.out.println(Calculus.getSum(59,78));
	}
}
Please, leave your questions, feedback and suggestions in the comments below!
Sarmaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

Sar Maroof's new book
Java quizmaster for beginners (English)

Java quizmaster voor beginners (Dutch)
Sar Maroof is the author of two Java books namely, Java quizmaster for beginners and A guide to build a Java application.
Experience with developing web applications since 2001
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster
Applied Science in Physics HBO Amsterdam
As well as Bachellor Science in Physics.
 Subscribe To sarmaroof RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

3 Comments

Add a Comment
  1. You coudln’t pay me to ignore these posts!

  2. Thank you Sar! Your website content and the design are great!

    1. Well I guess I don’t have to spend the weekend firing this one out!

Leave a Reply

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

Sarmaroof © 2017