Array and String
|A sequence of character data is called a string and is implemented in the Java environment by the String class (a member of the java.lang package). The character-counting program uses Strings in two different places. The first is in the definition of the main() method:|
|This code explicitly declares an array, named args, that contains String objects. The empty brackets indicate that the length of the array is unknown at compilation time because the array is passed in at runtime.|
|The second use of Strings in the example program is these two uses of literal strings|
|(a string of characters between double quotation marks " and "):|
|"Input has "
. . .
|The compiler implicitly allocates a String object when it encounters a literal string. So, the program implicitly allocates two String objects one for each of the two literal strings shown previously.|
|String String arrayOfStrings = new String;|
|The elements in this array are reference types, that is, each element contains a reference to a String object.|
|At this point, enough memory has been allocated to contain the String references, but no memory has been allocated for the Strings themselves. If we attempted to access one of arrayOfStrings elements at this point, we would get a NullPointerException because the array is empty and contains no Strings and no String objects.|
|We have to allocate the actual String objects separately:|
|for (int i = 0; i < arrayOfStrings.length; i ++)
arrayOfStrings[i] = new String("Hello " + i);
|objects are immutable--that is, they cannot be changed once they've been created. The java.lang package provides a different class, StringBuffer, which we can use to create and manipulate character data on the fly.|