Java Programming/API/java.lang.String
| Navigate Language Fundamentals topic: |
java.lang.String
String is a class built into the Java language defined in the java.lang package. It represents character strings. Strings are ubiquitous in Java. Study the String class and its methods carefully. It will serve you well to know how to manipulate them skillfully. String literals in Java programs, such as "abc", are implemented as instances of this class like this:
Code section 3.30: String example.
|
On the right hand side a String object is created represented by the string literal. Its object reference is assigned to the str variable.
Immutability
Strings are immutable; that is, they cannot be modified once created. Whenever it looks as if a String object was modified actually a new String was created. For instance, the String.trim() method returns the string with leading and trailing whitespace removed. Actually, it creates a new trimmed string and then returns it. Pay attention on what happens in Code section 3.31:
|
|
The trim() method call does not modify the object so nothing happens. It creates a new trimmed string and then throws it away.
|
|
The returned string is assigned to the variable. It does the job as the trim() method has created a new String instance.
Concatenation
The Java language provides special support for the string concatenation operator +, and for conversion of other objects to strings:
|
|
Integers will also be converted to String after the + operator:
|
|
Each Java object has the String toString() inherited from the Object class. This method provides a way to convert objects into Strings. Most classes override the default behavior to provide more specific (and more useful) data in the returned String:
|
|
Using StringBuilder/StringBuffer to concatenate strings
Remember that String objects are immutable objects. Once a String is created, it can not be modified, takes up memory until garbage collected. Be careful of writing a method like this :
Code section 3.36: Raw concatenation.
|
On the + operation a new String object is created at each iteration. Suppose coll contains the elements ["Foo", "Bar", "Bam", "Baz"]. The method creates eleven Strings:
"""Foo"" ""Foo ""Foo Bar"" ""Foo Bar ""Foo Bar Bam"" ""Foo Bar Bam ""Foo Bar Bam Baz"
Even though only last one is actually useful.
To avoid unnecessary memory use like this, use the StringBuilder class. It provides similar functionality to Strings, but stores its data in a mutable way. Only one StringBuilder object is created. Also because object creation is time consuming, using StringBuilder produces much faster code.
Code section 3.37: Concatenation with StringBuilder.
|
As StringBuilder isn't thread safe (see the chapter on Concurrency) you can't use it in more than one thread. Use StringBuffer instead, which does the same and is thread safe. However, as StringBuffer is slower, only use StringBuffer in a multi-thread environment. Moreover, only StringBuffer exists before Java 5.
Comparing Strings
Comparing strings is not as easy as it may first seem. We cannot just use a simple equality statement ==:
|
|
To test for equality, use the equals(Object) method inherited by every class and defined by String to return true if and only if the object passed in is a String containing the exact same data:
|
|
Remember that the comparison is case sensitive.
|
|
To order String objects, use the compareTo() method, which can be accessed wherever we use a String datatype. The compareTo() method returns a negative, zero, or positive number if the parameter is less than, equal to, or greater than the object on which it is called. Let's take a look at an example:
Code section 3.41: Order.
|
The code section 3.41 is comparing the String variable person1 to person2. If person1 was to be different, even in the slightest manner we will get a value above or below 0 depending on the exact difference. The result is negative if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. Take a look at the Java API for more details.
Splitting a String
Sometimes it is useful to split a string into separate strings, based on a regular expressions. The String class has a split() method, since Java 1.4, that will return a String array:
Code section 3.42: Order.
|
An other useful application could be to split the String text based on the new line character, so you could process the text line by line.
Substrings
It may also be sometimes useful to create substrings, or strings using the order of letters from an existing string. This can be done in two methods.
The first method involves creating a substring out of the characters of a string from a given index to the end:
|
|
The index of the first character in a string is 0. By counting from there, it is apparent that the character in index 3 is the second "f" in "coffee". This is known as the beginIndex. All characters from the beginIndex until the end of the string will be copied into the new substring.
The second method involves a user-defined beginIndex and endIndex:
|
|
The string returned by substring() would be "port". Please note that the endIndex is not inclusive. This means that the last character will be of the index endIndex-1. Therefore, in this example, every character from index 3 to index 6, inclusive, was copied into the substring.
String cases
The String class also allows for the modification of cases. The two methods that make this possible are toLowerCase() and toUpperCase().
|
|
These methods are useful to do a search which is not case sensitive:
|
|
See also
Java API: java.lang.String
Java API: java.lang.StringBuffer
Java API: java.lang.StringBuilder- Java Programming/API/java.lang.StringBuffer
- Java Programming/API/java.lang.StringBuilder