Objectives

Students will be able to:

  • understand that a reference variable which does not reference an object can reference null
  • understand that a reference to null means that any of the object's methods cannot be called
  • an attempt to call an object's method from a null will cause a null pointer exception

null

digital nothing

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.

Interestingly, if we declare an array of objects, Java will point each element in the array to null:

String[] names = new String[10];

for(int i = 0; i<names.length; i++)

System.out.println(names[i]);

We have an array of 10 nulls! Try it and see if you doubt it!

Did you know that if this was an integer array, we would have an array of 10 zeroes!

I wonder what would be placed in an array declared as an array of 10 booleans?

Dealing with null

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

Takeaways

  1. A function can take a reference to an array as a parameter.
  2. The function has no idea what data is in the array or how long it is!
  3. If it is an array of objects eg Strings, it may contain nulls.
  4. We cannot process nulls like we can with ordinary objects. We have to process them seperately.

Tags

for loopsvalue while loops if statements variable functions datatype parametercall a function