Nov 25, 2011

Strings in Java

 Java provides a smart implementation of character strings. A String object holds a fixed character string. Since these objects are read only, the implementation of String can be clever and return shared references into a pool of unique strings if it chooses to (you can use the intern() method to guarantee this). An object provides an array in which to manipulate string data; it grows as required when new data is appended or inserted.
A String is typically constructed using a double-quoted string literal:
String s = "My String";
However, Strings can also be constructed from arrays of char or byte:
char s_data[] = { 'M', 'y', ' ', 'S', 't', 'r', 'i', 'n', 'g' };
String s = new String( s_data );
Or from a StringBuffer:
String s = new String( my_strbuffer );
There are many useful methods for scanning strings and for extracting substrings:
String ring = "My String".substring(5, 9);     // extract substring "ring"
Notice how the indices start at 0, and notice that the lower bound is inclusive, the upper exclusive. Then the length of the substring is easily calculated as 9-5 = 4.
The length() method gives the length of a string.
The String class also has several static valueOf() methods that know how to convert various types into string representations. The notation is quite mnemonic:
String five = String.valueOf(5);
and so on. For more general objects, the method call String.valueOf(Object) uses the object's toString() method to perform the conversion. StringBuffer objects hold string data of variable length. You can append() any Object on the end, and the result is to append the string representation of that object to the StringBuffer (typically, you append a String anyway). You can insert() an Object at any index, and the string representation is inserted at that point, moving the rest of the buffer to make room. Although StringBuffer objects are handy for working with string data, all of the useful scanning methods are in the String class, so usually StringBuffer objects are an intermediate step to constructing a String. You can convert a StringBuffer to a string using the toString() method, or the constructor String(StringBuffer). Conversion of StringBuffers into Strings is smart: the array of character data is not copied unless and until a subsequent operation via a StringBuffer reference tries to alter the data, and then a copy is made transparently.
You can concatenate a String with another String or StringBuffer by using the + operator. Indeed, so long as one operand of the + operator is a String, then the other is converted into a String and the result is the concatenation of the two Strings:
String myaddress = 1234 + ' ' + "Birch St.," + ' ' + "Birchville";


Post a Comment