Sams Teach Yourself C in 21 Days

(singke) #1
To combine strings, a process known as concatenation, use the +operator. Java knows
you are working with strings and not numbers, so it knows to concatenate the strings
rather than trying to perform addition. Here are a few examples:
String fullName, firstName, lastName;
firstName = “Peter”;
lastName = “Aitken”;
fullName = firstName + “ “ + lastName;
The result of these operations are to place “Peter Aitken” within fullName.
String literals are written as you see above—text enclosed in double quotation marks. As
in C and C++, certain characters are represented by escape codes. The Java escape codes
are presented in Table B4.3

TABLEB4.3 Java character escape codes
Escape code Character represented
\b backspace
\t tab
\n new line
\f form feed
\r carriage return
\” double quotation mark
\’ single quotation mark
\\ backslash

String Methods
TheStringobject has a variety of methods that you use to work with string data. One
method you will find valuable is length(). The length()method returns the number of
characters in a string:
MyString = “Java programming”;
n = MyString.length();
//n now equals 16.
Note that the result of calling the length()method is 16. Unlike C and C++, a null
character is not counted.
Other methods let you modify a string, perform string comparisons, extract characters
from strings, and more. You should be able to find more details on the Stringclass and
its methods in the documentation that came with whatever Java development tool you are
using.
The program in Listing B4.1 demonstrates some of the methods of the Stringclass.

712 Bonus Day 4

39 448201x-Bonus4 8/13/02 11:19 AM Page 712

Free download pdf