Java Reference
In-Depth Information
last character to copy (i.e., copy up to, but not including , that index in the String ). The
substring returned contains a copy of the specified characters from the original String . An
index outside the bounds of the String causes a StringIndexOutOfBoundsException .
14.3.6 Concatenating Strings
String method concat (Fig. 14.7) concatenates two String objects (similar to using the +
operator) and returns a new String object containing the characters from both original
String s. The expression s1.concat(s2) at line 13 forms a String by appending the char-
acters in s2 to the those in s1 . The original String s to which s1 and s2 refer are not modified .
1
// Fig. 14.7: StringConcatenation.java
2
// String method concat.
3
4
public class StringConcatenation
5
{
6
public static void main(String[] args)
7
{
8
String s1 = "Happy " ;
9
String s2 = "Birthday" ;
10
11
System.out.printf( "s1 = %s%ns2 = %s%n%n" ,s1, s2);
12
System.out.printf(
13
"Result of s1.concat(s2) = %s%n" ,
s1.concat(s2)
);
14
System.out.printf( "s1 after concatenation = %s%n" , s1);
15
}
16
} // end class StringConcatenation
s1 = Happy
s2 = Birthday
Result of s1.concat(s2) = Happy Birthday
s1 after concatenation = Happy
Fig. 14.7 | String method concat .
14.3.7 Miscellaneous String Methods
Class String provides several methods that return String s or character arrays containing
copies of an original String 's contents which are then modified. These methods—none
of which modify the String on which they're called—are demonstrated in Fig. 14.8.
1
// Fig. 14.8: StringMiscellaneous2.java
2
// String methods replace, toLowerCase, toUpperCase, trim and toCharArray.
3
4
public class StringMiscellaneous2
5
{
6
public static void main(String[] args)
7
{
Fig. 14.8 | String methods replace , toLowerCase , toUpperCase , trim and toCharArray .
(Part 1 of 2.)
 
 
 
Search WWH ::




Custom Search