2

I have two methods which both print the contents on arrays, one is declared as public void and the other static void. However when I call these methods from the main program class they exhibit different behavior.

public void:

  public void listStudent() {
    for (int i = 0;i < 10;i++) {
      if (studentNamesArray[i] != null) {
        System.out.println(studentNamesArray[i]);
        for(int y = 0;y < 3;y++) {
          System.out.println(studentMarksArray[i][y]);
        }
      }
    }
  }

Static void:

  static void printArrays() {
    for (int i = 0;i < 10;i++) {
      if (studentNamesArray[i] != null) {
        System.out.println(studentNamesArray[i]);
        for(int y = 0;y < 3;y++) {
          System.out.println(studentMarksArray[i][y]);
        }
      }
    }
  }

The public void when called results in a nullPointerEception error while the static void call doesn't print anything (as is expected). In both cases the arrays are empty however if I store a value and then delete that value the public void method then prints nothing as expected. i.e. public void only results in an error if it's called before an object is created even if that object is then immediately deleted from the array.

Why do these methods behave in different ways? Is it considered bad practice to declare a method static void?

Colin747
  • 4,955
  • 18
  • 70
  • 118

1 Answers1

2

Check how you are calling the method. For a public method that is non-static, the object must be initialized.

Take, for example, a class like this:

public class CustomObject
{
  private static String[][] studentNamesArray = null;

  public void listStudents() {...}
  public static void printArrays() {...}
}

If you were to make this call:

CustomObject.printArrays();

The call would work (and print nothing) because the method is static, and so always exists when referencing that CustomObject.

If you were to make this call:

CustomObject co;
co.listStudents();

it would fail with a null pointer exception because the CustomObject "co" had not been initialized. One cannot make method calls on a null object.

Also, the array must be initialized. It is hard to tell what is happening in your program without the surrounding code, but the call to:

if( studentNamesArray[i] == null )

will produce a NPE if the array is not initialized. One cannot find the [i]th instance of a null array. That is true for the static and local versions of the method.

clay
  • 5,917
  • 2
  • 23
  • 21