Java Reference
In-Depth Information
displays
The length of Welcome to Java is 15
Note
When you use a string, you often know its literal value. For convenience, Java allows
you to use the string literal to refer directly to strings without creating new variables.
Thus, "Welcome to Java".length() is correct and returns 15 . Note that ""
denotes an empty string and "".length() is 0 .
string literal
empty string
4.4.2 Getting Characters from a String
The s.charAt(index) method can be used to retrieve a specific character in a string s ,
where the index is between 0 and s.length()-1 . For example, message.charAt(0)
returns the character W , as shown in FigureĀ 4.1. Note that the index for the first character in
the string is 0 .
charAt(index)
Indices
message
0123456789 0 1 2 3 4
We l
come
t
o
Java
message.charAt(0)
message.length() is 15
message.charAt(14)
F IGURE 4.1
The characters in a String object can be accessed using its index.
Caution
Attempting to access characters in a string s out of bounds is a common pro-
gramming error. To avoid it, make sure that you do not use an index beyond
s.length() - 1 . For example, s.charAt(s.length()) would cause a
StringIndexOutOfBoundsException .
string index range
4.4.3 Concatenating Strings
You can use the concat method to concatenate two strings. The statement shown below, for
example, concatenates strings s1 and s2 into s3 :
String s3 = s1.concat(s2);
s1.concat(s2)
Because string concatenation is heavily used in programming, Java provides a convenient
way to accomplish it. You can use the plus ( + ) operator to concatenate two strings, so the
previous statement is equivalent to
String s3 = s1 + s2;
s1 + s2
The following code combines the strings message , " and " , and "HTML" into one string:
String myString = message + " and " + "HTML" ;
Recall that the + operator can also concatenate a number with a string. In this case, the
number is converted into a string and then concatenated. Note that at least one of the operands
must be a string in order for concatenation to take place. If one of the operands is a nonstring
concatenate strings and
numbers
 
 
Search WWH ::




Custom Search