A String array, students, is waitng to be processed.
A reference to the array is sent to a function and the function will count how many students are called Jack.
public static int countJack(String[] studentNames){
int count = 0;
for(int i = 0; i<studentNames.length; i++){
if(students[i].equals("Jack")){ //maybe better to use equalsIgnoreCase
count = count + 1;
}
}
return count;
}
As you can see in the animation, each String object in the array gives the programmer an opportunity to use String methods such as equals(), length() etc.
But look at students[2]. There is no String object - just something called null.
Null just means digital nothing but it allows reference variables to stay alive in a program when there is no object to point to.
The code above looks logical and should work fine. But it won't. Null does not have a equals() method.
So, we will get a NULL POINTER EXCEPTION, which is a kind of error and the program will crash unless we catch the error!
To deal with this situation, we could do this:
public static int countJack(String[] studentNames){
int count = 0;
for(int i = 0; i<studentNames.length; i++){
if(students[i]!=null && students[i].equalsIgnoreCase("jack")){
count = count + 1;
}
}
return count;
}
SAFE!
So, when processing arrays of objects, don't forget that an element may contain null, and we should write code to deal with that scenario.
Here is the Main.java file from the video