3. Manipulating StringsMuch of what you do in any programming language involves the manipulation of strings. Other than numeric data, nearly all data is accessed as a string. Quite often, even numeric data is treated as a simple string. It is difficult to imagine being able to write a complete program without making use of strings. The phrases in this chapter show you some common tasks involving strings. The Java language has strong built-in support for strings and string processing. Unlike the C language, strings are built-in types in the Java language. Java contains a String class that is used to hold string data. Strings in Java should not be thought of as an array of characters as they are in C. Whenever you want to represent a string in Java, you should use the String class, not an array. An important property of the String class in Java is that once created, the string is immutable. This means that once created, a Java String object cannot be changed. You can reassign the name you've given a string to another string object, but you cannot change the string's contents. Because of this, you will not find any set methods in the String class. If you want to create a string that you can add data to, such as you might in some routine that builds up a string, you should use the StringBuilder class if you are using JDK 1.5, or the StringBuffer class in older versions of Java, instead of the String class. The StringBuilder and StringBuffer classes are mutable; thus you are allowed to change their contents. It is very common to build strings using the StringBuilder or StringBuffer class and to pass or store strings using the String class. |