In general, methods may be classified under two categories:

·    The ones whose behaviour depends on the state of the object on which they are defined,

·     And the ones that do not depend on the state of the object.

Consider the example of the ball game described in here section. A player may be given the choice to select the colour of the balls. This colour choice will be applied to all the balls he creates during the game. Thus, if we define a setDefaultColor method for setting the colour of a ball, the method may be attached to the Ball class rather than every object of the Ball type. Such a method is defined using the static keyword, as will be explained further.

Now, consider a method that sets the velocity of the motion for a ball. The velocity will obviously depend on the current state of the game and will be independently set for each ball on the board game. Therefore, we’ll want to define a method called setVelocity that operates on an instance of a Ball class. This type of method is a non-static method—a method that does not use the static keyword. We discuss both types of methods here. First, though, let’s look at a few more situations where the methods need to be declared with the static keyword.

Sometimes we may want to execute program code without creating a class instance. A typical example of this is the declaration of the main method in our program code, as shown here:

public static void main(String[] args)                 

Because the program execution begins with the main method, we need to run it before we can create an instance of our application class. Therefore, the method is declared using the static keyword.

Another example is the use of mathematical functions. To compute an exponential or a logarithm, we would want to call the appropriate function directly instead of creating a class instance and then invoking a method on that instance. For example, Java libraries define a class called Math in the java.lang package. The Math class has several mathematical functions defined in terms of the class methods. All these methods are declared static so that they can be invoked without instantiating the Math class. For example, to determine a logarithm of a given number, we would use the method log, which is invoked as follows:


This statement would print the log of 5.0 on our terminal. To determine the square root of a given number, we would use the following:


Both the log and sqrt methods of the Math class are static and can therefore be invoked without an instance of the Math class being created.

Now that we have discussed the need for static methods, let’s go back to our ball game example. Here is an enhanced ball game that creates a random number of balls on each run.

Out of the total number of balls created, a randomly selected number of them will be red and the rest green. Each ball has a constant radius, which is also set randomly on each run. As we can imagine, the radius is an appropriate candidate for creating a class field (static) with corresponding getter/setter static methods. Because the colour of each ball is randomly set, it becomes the instance property (non-static). Finally, we set the velocity of motion for each ball after it is created. Setting the velocity of the ball will be an instance method (non-static) because it operates on an individual object.

import java.awt.Color; 

class Ball {
                     private static int count = 0;
                     private static int redBallCount = 0;
                     private static int greenBallCount = 0;
                     private static int radius = 0;
                     private Color defaultColor;

                     public static int getRedBallCount() {

                             return redBallCount;

                     public static int getGreenBallCount() {
                             return greenBallCount;


                     public static int getRadius() {
                             return radius;


                     public static void setRadius(int radius) {

                             Ball.radius = radius;


                     public Ball(Color color) {
                             if (color == Color.RED) {
                                      this.defaultColor = Color.RED;
                             } else {
                                      this.defaultColor = Color.GREEN;


                     public void setVelocity(double v) {
                             String strColor = null;
                             if (defaultColor == Color.RED) {
                                      strColor = "Red";

                             } else {
                                      strColor = "Green";

                             System.out.printf("Ball #%d:%-10s velocity set to %.02f%n", count,
                                                       strColor, v);

public class EnhancedBallGame {

                     public static void main(String[] args) {
                             int numberOfBalls = (int) (Math.random() * 10);
                             int radius = (int) (Math.random() * 20) + 1;
                             System.out.printf("Creating %d balls of radius %d%n", numberOfBalls,
                             for (int i = 0; i < numberOfBalls; i++) {
                                      int number = (int) (Math.random() * 2);
                                      if (number == 0) {
                                                new Ball(Color.RED).setVelocity(Math.random() * 10);
                                      } else {


                             System.out.println("Number of red balls created: "
                                                + Ball.getRedBallCount());
                             System.out.println("Number of green balls created: "
                                                + Ball.getGreenBallCount());



 The Ball class declares several fields—count, redBallCount, greenBallCount, radius, and defaultColor. The first four are static and the last one is non-static. The defaultColor field holds the color value of each individual ball and is therefore set to be an instance variable. The count field, as in the earlier example, tracks each ball that’s created and at the end holds the total number of balls. The redBallCount and greenBallCount fields hold the total number of red and green balls created, respectively. The radius field is common to all balls and is therefore declared static. The class defines the desired getter/setter methods on these fields.

The class constructor takes one parameter of the Color type. Note that Color is a Java-supplied class defined in the java.awt package. The Color class defines several static fields to represent different colors. The constructor increments the static field count to account for the newly created object. The value of the input argument is copied into the defaultColor field. If this input argument is of type Color.RED, we increment the count of red balls; otherwise, we increment the count of green balls. Both these counts are static fields and therefore their values are retained during each instantiation of the Ball class.

Finally, the Ball class declares one non-static method called setVelocity that takes one parameter representing the velocity value to be set. This method simply prints the value of the velocity along with the ball number on which the velocity is set to the user’s console. We also print the color value of each ball.

In the main method of the EnhancedBallGame class, we set the number of balls to be created using the randomizer. We set the radius for all the balls to be created by using the randomizer. Here, setRadius is a static method of the class that sets the value of the static field radius. This value will be common to all instances of the Ball class. Next, we create the balls by setting up a for loop. We select between a red and green ball by once again using the randomizer.

We use the new keyword to instantiate the Ball class. We call the class constructor by sending either the red or green color value to it. After the class is instantiated, we call the setVelocity non-static method on the created instance to set the velocity of the created ball. The velocity value is set again using the randomizer. After all the balls have been created, the program prints a tally of the red and green balls. A typical output is shown next. Note that this output varies on each run.

Creating 7 balls of radius 20

Ball #1:Green velocity set to 5.82
Ball #2:Green velocity set to 1.11
Ball #3:Green velocity set to 1.05
Ball #4:Red velocity set to 6.79
Ball #5:Green velocity set to 7.33
Ball #6:Green velocity set to 8.88
Ball #7:Red velocity set to 1.23
Number of red balls created: 2
Number of green balls created: 5
  Modified On Nov-29-2017 09:04:16 AM

Leave Comment