Array and String
 
Object arrays
 
Object array are declared with the class name as the type.
 
For example
String[] names = new String[5];
 
 
Constructs an array of 5 String object references. It is important to understand that no String objects are created by this declaration. We have simply created an array of null object references which may later be assigned to individual String objects (as shown by the following diagram).
 
 
The statement
names[3] = new String("Hello World!");
 
would instantiate a String object and assign it to the fourth element in the names array (which would look like the following).
 
 
To display the value of this particular String object, one might code
System.out.println(names[3]);
 
which retrieves the String object referenced by the fourth element in the names array.
 
Object array are arrays of object references. Each element is either the reference of an instantiated object or is null. The general syntax to access an instance method of the object being referenced is
array-identifier[index].method-name(arguments)
 
For example,
To determine the length of the encapsulated string in the fourth element of the names array one would code the expression
names[3].length()
 
Object array can result in runtime errors if improperly used. In addition to an ArrayIndexOutOfBoundsException, it is possible for a NullPointerException to occur if an attempt is made to reference an object when the object reference is null.
 
Example:
Attempting to call an instance method of an object that doesn't exist.
 
public class AppObj
{
public static void main(String[] args)
{
String[] names = new String[5];
System.out.println("Length of first string: " + names[0].length());
}
}
 
 
Object array can be constructed from a value list. This requires the instantiation or the existence of the objects to be referenced by each array element.
 
For example,
String aString = new String("def");
String[] x = {new String("abc"), aString, "xyz"};
 
 

creates a three element array of String object references. The first element references a String object having the value " abc ", the second element references a String object having the value " def ", and the third references the String object in the literal pool having the value " xyz ".