Concatenating Strings

   

Another way you can manipulate strings is to concatenate (in other words, join) them. So, when you concatenate two strings, you get a new string that contains both of the original strings. Look at these lines of Java source code, for example. There are several ways to concatenate Strings together. The first is the concat method on the String class.

 String str1 = "This is one string"; String str2 = str1.concat(" and this is another."); 

If this code fragment was executed, str2 would contain This is one string and this is another and str1 would remain unchanged. As you can see, the concat method's single argument is the string to concatenate with the original string.

To make things simpler, the String class defines an operator, the plus sign (+), for concatenating strings. By using this operator, you can join strings in a more intuitive way. Here's an example:

 String str1 = "This is one string"; String str2 = str1 + " and this is another."; 

This code segment results in exactly the same strings as the preceding concat example. Note that you can use the concatenation operator many times in a single line, like this:

 String str = "This " + "is " + "a test"; 

As you'll see in the StringBuffer section shortly, there is another alternative to using the concat method or the "+" operator when you need to concatenate many Strings together.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net