Java Reference
In-Depth Information
Self-Test Exercises
27. What is a reference type? Are class types reference types? Are primitive types
(such as int ) reference types?
28. When comparing two objects of a class type to see if they are “equal” or not,
should you use == or the method equals ?
29. When comparing two objects of a primitive type (such as int ) to see if they are
“equal” or not, should you use == or the method equals ?
30. Can a method with an argument of a class type change the values of the instance
variables in the object named by the argument? For example, if the argument is
of type ToyClass defined in Display 5.11, can the method change the name of its
argument?
31. Suppose a method has a parameter of type int and the method is given an int
variable as an argument. Could the method have been defined so that it changes
the value of the variable given as an argument?
The Constant null
The constant null is a special constant that may be assigned to a variable of any class
type. It is used to indicate that the variable has no “real value.” If the compiler insists
that you initialize a variable of a class type and there is no suitable object to initialize it
with, you can use the value null , as in the following example:
null
YourClass yourObject = null ;
It is also common to use null in constructors to initialize instance variables of a class
type when there is no obvious object to use. We will eventually see other uses for the
constant null .
Note that null is not an object. It is like a reference (memory address) that does not
refer to any object (does not name any memory location). So if you want to test
whether a class variable contains null , you use == or != ; you do not use an equals
method. For example, the following correctly tests for null :
if (yourObject == null )
System.out.println("No real object here.");
null
null is a special constant that can be used to give a value to any variable of any class
type. The constant null is not an object but a sort of placeholder for a reference to an
object. Because it is like a reference (memory address), you use == and != rather than the
method equals when you test to see whether a variable contains null .
Search WWH ::




Custom Search