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?