Saturday, December 10, 2011

Java's character and assorted string classes support text-processing - 10


Interning Strings in the common string memory pool poses a problem. Because that pool does not permit duplicates, what happens if code interned a String and then changed that object's contents? The pool might then contain two Strings with the same contents, which defeats the string memory savings that internment in the pool provides. For that reason, Java does not let code modify a String. Thus, Strings are immutable, or unchangeable.
Note
Some String methods (such as public String toUpperCase(Locale l)) appear to modify a String, but in actuality, don't. Instead, such methods create a new String containing a modified string.

String method sampler
String contains more than 50 methods (not including constructors), however we'll only examine 13:
Note
Many String methods require an index (also known as an offset) argument for accessing a character in the String object's value array (or a character array argument). That index/offset is always zero-based: index/offset 0 refers to the array's first character.

  • public char charAt(int index) extracts the character at the index position in the current String object's value array and returns that character. This method throws an IndexOutOfBoundsException object if index is negative or equals/exceeds the string's length. Example: String s = "Hello"; System.out.println (s.charAt (0)); (output: H).
public int compareToIgnoreCase(String anotherString) performs a lexicographic (dictionary order) case-insensitive comparison between characters in the current String's value array and the value array of the anotherString-referenced String. A zero return value indicates that both arrays contain the same characters; a positive return value indicates that the current String's value array identifies a string that follows the string that anotherString's value array represents; and a negative value indicates that anotherString's string follows the current String's string. This method throws a NullPointerException object if anotherString is null. Example: String s = "abc"; String t = "def"; System.out.println (s.compareToIgnoreCase (t)); (output: -3).

No comments: