Java Reference
In-Depth Information
Yo u can call the toString() method directly, or, alternatively, the “+
operator calls the toString() method whenever the variable refers to an object.
Forexample, consider
Double aDouble = 5.0;
String aDoubleString =" aDouble =" + aDouble;
The plus operator in the second line invokes the toString() method of the
Double object aDouble . This results in aDoubleString referencing the
string “aDouble = 5.0 .
4.7 More about arrays
Here we look at other aspects of Java arrays and at tools to use with them. Note
that like much of Java syntax, arrays at first glance seem very similar to those
in C/C
.However, there are several differences from these languages in how
Java arrays are built and how they work.
++
4.7.1 Object arrays
In the previous chapter we introduced arrays of primitive types, which generally
behave in the manner that is expected of such arrays. For example, to create an
array of ten integers we could use the following:
int[] iArray = new int[10];
This sets aside ten int type memory locations, each containing the value 0.
Forarraysofobjects, however, the array declaration only creates an array of
references for that particular object type. It does not create the actual objects
of that type. Creating the objects themselves requires an additional step. For
example, let's say we want to create an array of five String objects. We first
create a String type array:
String[] strArray = new String[5];
When the array is created, five memory locations are set aside to contain object
references of the String type with the expectation that each reference will
eventually “point” to a String object. But initially, each element contains the
special null reference value; that is, it points nowhere .Soifwefollowed the
above declaration with an attempt to use a String method, as in
int numChars = strArray[0].length ();
an error message results:
Exception in thread " main " java.lang.NullPointerException at
ArrayTest.main (ArrayTest.java:8)
Search WWH ::




Custom Search