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).
No comments:
Post a Comment