String
is a class built into the Java language defined in thejava.lang
package. It represents character strings. Strings are ubiquitous in Java. Study theString
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.81: String example.Stringstr="This is string literal"; |
On the right hand side a String object is created represented by the string literal. Its object reference is assigned to thestr
variable.
Strings areimmutable; that is, they cannot be modified once created. Whenever it looks as if a String object was modified actually a new String object was created. For instance, theString.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 inCode section 3.82:
 | Code section 3.82: Immutability.StringbadlyCutText=" Java is great. ";System.out.println(badlyCutText);badlyCutText.trim();System.out.println(badlyCutText); |
|  | Output for Code section 3.82 Java is great. Java is great. |
|
Thetrim()
method call does not modify the object so nothing happens. It creates a new trimmed string and then throws it away.
 | Code section 3.83: Assignment.StringbadlyCutText=" Java is great. ";System.out.println(badlyCutText);badlyCutText=badlyCutText.trim();System.out.println(badlyCutText); |
|  | Output for Code section 3.83 Java is great. Java is great. |
|
The returned string is assigned to the variable. It does the job as thetrim()
method has created a newString
instance.
The Java language provides special support for the string concatenation with operator+
:
 | Code section 3.84: Examples of concatenation.System.out.println("First part");System.out.println(" second part");Stringstr="First part"+" second part";System.out.println(str); |
|  | Output for Code section 3.84First part second partFirst part second part |
|
The concatenation is not always processed at the same time.Raw string literals concatenation is done at compile time, hence there is a single string literal in the byte code of the class. Concatenation with at least one object is done at runtime.
+
operator can concatenate other objects with strings. For instance, integers will be converted to strings before the concatenation:
 | Code section 3.85: Concatenation of integers.System.out.println("Age="+25); |
|  | Output for Code section 3.85Age=25 |
|
Each Java object has theString toString()
inherited from theObject
class. This method provides a way to convert objects intoString
s. Most classes override the default behavior to provide more specific (and more useful) data in the returnedString
:
 | Code section 3.86: Concatenation of objects.System.out.println("Age="+newInteger(31)); |
|  | Output for Code section 3.86Age=31 |
|
Remember thatString
objects are immutable objects. Once aString
is created, it can not be modified, takes up memory until garbage collected. Be careful of writing a method like this:
 | Code section 3.87: Raw concatenation.publicStringconvertToString(Collection<String>words){Stringstr="";// Loops through every element in words collectionfor(Stringword:words){str=str+word+" ";}returnstr;} |
On the+
operation a newString
object is created at each iteration. Supposewords
contains the elements["Foo", "Bar", "Bam", "Baz"]
. At runtime, the method creates thirteenString
s:
""
"Foo"
" "
"Foo "
"Foo Bar"
" "
"Foo Bar "
"Foo Bar Bam"
" "
"Foo Bar Bam "
"Foo Bar Bam Baz"
" "
"Foo Bar Bam Baz "
Even though only the last one is actually useful.
To avoid unnecessary memory use like this, use theStringBuilder
class. It provides similar functionality toString
s, but stores its data in a mutable way. Only oneStringBuilder
object is created. Also because object creation is time consuming, usingStringBuilder
produces much faster code.
 | Code section 3.88: Concatenation withStringBuilder .publicStringconvertToString(Collection<String>words){StringBuilderbuf=newStringBuilder();// Loops through every element in words collectionfor(Stringword:words){buf.append(word);buf.append(" ");}returnbuf.toString();} |
AsStringBuilder
isn't thread safe (see the chapter onConcurrency) you can't use it in more than one thread. For a multi-thread environment, useStringBuffer
instead which does the same and is thread safe. However,StringBuffer
is slower so only use it when it is required. Moreover, before Java 5 onlyStringBuffer
existed.
Comparing strings is not as easy as it may first seem. Be aware of what you are doing when comparingString
's using==
:
 | Code section 3.89: Dangerous comparison.Stringgreeting="Hello World!";if(greeting=="Hello World!"){System.out.println("Match found.");} |
|  | Output for Code section 3.89Match found. |
|
The difference between the above and below code is that the above code checksto see if theString
's are the same objects in memory which they are. This is as a result of the fact thatString
's are stored in a place in memory called the String Constant Pool. If thenew
keyword is not explicitly used when creating theString
it checks to see if it already exists in the Pool and uses the existing one. If it does not exist, a new Object is created. This is what allows Strings to be immutable in Java.To test for equality, use theequals(Object)
method inherited by every class and defined byString
to returntrue
if and only if the object passed in is aString
contains the exact same data:
 | Code section 3.90: Right comparison.Stringgreeting="Hello World!";if(greeting.equals("Hello World!")){System.out.println("Match found.");} |
|  | Output for Code section 3.90Match found. |
|
Remember that the comparison is case sensitive.
 | Code section 3.91: Comparison with lowercase.Stringgreeting="Hello World!";if(greeting.equals("hello world!")){System.out.println("Match found.");} |
|  | Output for Code section 3.91 |
|
To orderString
objects, use thecompareTo()
method, which can be accessed wherever we use a String datatype. ThecompareTo()
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.92: Order.Stringperson1="Peter";Stringperson2="John";if(person1.compareTo(person2)>0){// Badly orderedStringtemp=person1;person1=person2;person2=temp;} |
Thecode section 3.92 is comparing the String variableperson1
toperson2
. Ifperson1
is 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 positive if this String object lexicographically follows the argument string. Take a look at theJava API for more details.
Sometimes it is useful to split a string into separate strings, based on aregular expressions. TheString
class has asplit()
method, since Java 1.4, that will return a String array:
 | Code section 3.93: Order.Stringperson="Brown, John:100 Yonge Street, Toronto:(416)777-9999";...String[]personData=person.split(":");...Stringname=personData[0];Stringaddress=personData[1];Stringphone=personData[2]; |
Another useful application could be tosplit the String text based on the new line character, so you could process the text line by line.
It may also be sometimes useful to createsubstrings, 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:
 | Code section 3.94: Truncating string.Stringstr="coffee";System.out.println(str.substring(3)); |
|  | Output for Code section 3.94fee |
|
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 thebeginIndex
. All characters from thebeginIndex
until the end of the string will be copied into the new substring.
The second method involves a user-definedbeginIndex
andendIndex
:
 | Code section 3.95: Extraction of string.Stringstr="supporting";System.out.println(str.substring(3,7)); |
|  | Output for Code section 3.95port |
|
The string returned bysubstring()
would be "port".
Please note that the endIndex isnot inclusive. This means that the last character will be of the indexendIndex-1
. Therefore, in this example, every character from index 3 to index 6, inclusive, was copied into the substring.
 | It is easy to mistake the methodsubstring() forsubString() (which does not exist and would return with a syntax error on compilation).Substring is considered to be one word. This is why the method name does not seem to follow the common syntax of Java. Just remember that this style only applies to methods or other elements that are made up of more than one word. |
TheString
class also allows for the modification of cases. The two methods that make this possible aretoLowerCase()
andtoUpperCase()
.
 | Code section 3.96: Case modification.Stringstr="wIkIbOoKs";System.out.println(str.toLowerCase());System.out.println(str.toUpperCase()); |
|  | Output for Code section 3.96wikibooksWIKIBOOKS |
|
These methods are useful to do a search which is not case sensitive:
 | Code section 3.97: Text search.Stringword="Integer";Stringtext="A number without a decimal part is an integer."+" Integers are a list of digits.";...// Remove the caseStringlowerCaseWord=word.toLowerCase();StringlowerCaseText=text.toLowerCase();// Searchintindex=lowerCaseText.indexOf(lowerCaseWord);while(index!=-1){System.out.println(word+" appears at column "+(index+1)+".");index=lowerCaseText.indexOf(lowerCaseWord,index+1);} |
 | Output for Code section 3.97Integer appears at column 38.Integer appears at column 47. |
Test your knowledge
Question 3.12: You have mail addresses in the following form:<firstName>.<lastName>@<companyName>.org
Write theString getDisplayName(String)
method that receives the mail string as parameter and returns the readable person name like this:LASTNAME Firstname
Answer
 | Answer 3.12:getDisplayName() publicstaticStringgetDisplayName(Stringmail){StringdisplayName=null;if(mail!=null){String[]mailParts=mail.split("@");StringnamePart=mailParts[0];String[]namesParts=namePart.split("\\.");// The last nameStringlastName=namesParts[1];lastName=lastName.toUpperCase();// The first nameStringfirstName=namesParts[0];StringfirstNameInitial=firstName.substring(0,1);firstNameInitial=firstNameInitial.toUpperCase();StringfirstNameEnd=firstName.substring(1);firstNameEnd=firstNameEnd.toLowerCase();// ConcatenationStringBuilderdisplayNameBuilder=newStringBuilder(lastName).append(" ").append(firstNameInitial).append(firstNameEnd);displayName=displayNameBuilder.toString();}returndisplayName;} |
- We only process non null strings,
- We first split the mail into two parts to separate the personal information from the company information and we keep the name data,
- Then we split the name information to separate the first name from the last name. As the
split()
method use regular expression and.
is a wildcard character, we have to escape it (\.
). However, in a string, the\
is also a special character, so we need to escape it too (\\.
), - The last name is just capitalized,
- As the case of all the first name characters will not be the same, we have to cut the first name. Only the first name initial will be capitalized,
- Now we can concatenate all the fragments. We prefer to use a
StringBuilder
to do that.