350 likes | 481 Views
4.4 The Null Reference. It is possible to declare names for object references and not assign object references to them. Such names literally refer to nothing at all. It is also possible for a reference to be assigned the special value “null”.
E N D
It is possible to declare names for object references and not assign object references to them. • Such names literally refer to nothing at all. • It is also possible for a reference to be assigned the special value “null”. • Although no object exists, this is not the same as referring to nothing at all.
A programmer can make such an assignment and in certain situations the system will make such an assignment by default. • Even if you choose not to use null in your code, you need to know about it since the system may make use of it. • Various errors can arise from improper use of null references, and it is important to be able deal with these errors, and distinguish them from errors arising from references to nothing at all.
Here is a null reference assignment: • Cup3 myCup; • myCup = null;
This could be used, for example to dispose of a previously constructed object without creating a new one: • Cup3 myCup; • myCup = new Cup3(4); • … • myCup = null;
What follows is a class definition and a set of examples showing various different things that can happen within programs that use the class. • These things are either the result of an object name referring to nothing at all, or a null reference. • Here is the class:
public class Shampoo • { • private String kind; • private int rating; • public Shampoo(String kindIn) • { • kind = kindIn; • } • public Shampoo(intratingIn) • { • rating = ratingIn; • }
public void setKind(String kindIn) • { • kind = kindIn; • } • public String getKind() • { • return kind; • } • public void setRating(intratingIn) • { • rating = ratingIn; • } • public intgetRating() • { • return rating; • } • }
Here is the first example. • It illustrates that using an object name as a parameter in a method call does not work if the object does not exist. • The compiler can detect a problem like this. • public class Test1 • { • public static void main(String[] args) • { • Shampoo myShampoo; • System.out.println(myShampoo); • } • }
In the Eclipse development environment the line of code with the error will be marked with a red X box at the left, and there will also be an error message in the Problems tab at the bottom. • If you move the mouse over the red X box by the line of code, the box shown below with the explanatory messages will appear:
Error messages are occasionally worded in an unhelpful way, or sometimes the compiler can't determine absolutely what might be wrong. • This error message is worded helpfully, but it says "may" just because something else might be wrong.
But in this case, the fact that myShampoo does not refer to an actual object is the problem, and that is indicated by the error message. • If the compiler ends with such an error, no program is created and it is impossible to run the code. • If you try to run the code anyway, this is what you'll see:
If you press the proceed button, the system will repeat the compiler error message.
Here is the second example, which illustrates a similar situation. • An object name is declared, but no object exists, and a method is called on that name. • public class Test2 • { • public static void main(String[] args) • { • Shampoo myShampoo; • intsomeRating = myShampoo.getRating(); • System.out.println(someRating); • } • }
The second example generates exactly the same kind of compiler error as the first example, and no program results.
Now consider the third example. • It is similar to the first example, in that it considers the case where an object reference is to be passed as a parameter. • No object exists but in this case the reference has been given the value null. • public class Test3 • { • public static void main(String[] args) • { • Shampoo myShampoo = null; • System.out.println(myShampoo); • } • }
The program compiles and runs successfully. • It prints out the value of the reference myShampoowith no problem. • Here is the output: • null
Now consider the fourth example. • It is similar to the second example, in that it considers the case where a method is to be called on an object reference. • No object exists but in this case the reference has been given the value null. • public class Test4 • { • public static void main(String[] args) • { • Shampoo myShampoo = null; • intsomeRating = myShampoo.getRating(); • System.out.println(someRating); • } • }
This program compiles without a red X box, but the compiler does mark the middle line of code with this warning message:
The system will still let you run the program even though it is not possible to successfully make a method call on a null reference. • If you run the code, this message will appear in the Console tab at the bottom of the environment. • Notice that this is a runtime error, not a compiler error. • That's why it appears in the Console, where output normally appears, not in the Problems tab. • Exception in thread "main" java.lang.NullPointerException • at TestShampoo.main(TestShampoo.java:5)
Even though you hope to catch all of your problems up front through compiler warnings, and so on, it is worthwhile to be aware of the NullPointerException message and know that it signifies, in simple terms, that in your code you tried to call a method on an object reference that contained the null value. • As the next example will show, this kind of problem can crop up.
The first four examples were relatively straightforward. • They illustrate problems that a beginning programmer should be able to manage. • However, there is a more subtle source of null references in programs. • The Shampoo class has an instance variable that is a string. • Since String is a class, this instance variable is an object reference.
The Shampoo class has a constructor that takes a single int as a parameter. • In the code for that constructor, nothing is done to explicitly initialize the String instance variable. • If any initialization does occur, it is by default. • The key point is that the system will initialize the String instance variable by default, to the value null.
Now consider the fifth example, which makes use of this constructor. • public class Test5 • { • public static void main(String[] args) • { • Shampoo myShampoo; • String someKind; • intsomeRating = 5; • myShampoo = new Shampoo(someRating); • someKind = myShampoo.getKind(); • System.out.println(someKind); • } • }
This program runs successfully because it is possible to have a null reference as an explicit parameter. • However, it illustrates that null references can arise in programs from unexpected sources. • The sixth example illustrates how a program may fail due to a null reference that was obtained from elsewhere.
public class Test6 • { • public static void main(String[] args) • { • Shampoo myShampoo; • String someKind; • intsomeRating = 5; • myShampoo = new Shampoo(someRating); • someKind = myShampoo.getKind(); • System.out.println(someKind); • int length = someKind.length(); • System.out.println(length); • } • }
The program runs correctly through this line of code: • System.out.println(someKind);
It causes this output in the Console tab at the bottom, with "null" being the result of this last successfully executed line of code: • null • Exception in thread "main" java.lang.NullPointerException • at TestShampoo.main(TestShampoo.java:15)
The program then encounters a problem in this line of code: • intlength = someKind.length(); • This is what causes this runtime error message: • Exception in thread "main" java.lang.NullPointerException • at TestShampoo.main(TestShampoo.java:15)
The error is the same as the one noted before. • It is not possible to call a method on a null reference. • The compiler is not all-knowing. • It can only see one level deep—it can't see what a reference may contain at run time. • Only the programmer can foresee and avoid problems like this, or correct them after they have been discovered.
References that refer to nothing and null references are possible in Java. • The default initialization of instance variables in objects can cause null references in programs. • This is a subtle source of problems that the programmer needs to be aware of.
The examples above are not exhaustive, but they show some representative cases and the results that they lead to. • If you encounter an error message similar to one of those shown above, you may be able to figure out what your problem is by looking at the examples again.