Java Reference
In-Depth Information
Line 20 uses String method toLowerCase to return a new String object with lower-
case letters where corresponding uppercase letters exist in s2 . The original String remains
unchanged. If there are no characters in the original String to convert, toLowerCase
returns the original String .
Line 23 uses String method trim to generate a new String object that removes all
white-space characters that appear at the beginning and/or end of the String on which
trim operates. The method returns a new String object containing the String without
leading or trailing white space. The original String remains unchanged. If there are no
white-space characters at the beginning and/or end, trim returns the original String .
Line 26 uses String method toCharArray to create a new character array containing
a copy of the characters in s1 . Lines 29-30 output each char in the array.
14.3.8 String Method valueOf
As we've seen, every object in Java has a toString method that enables a program to obtain
the object's string representation . Unfortunately, this technique cannot be used with prim-
itive types because they do not have methods. Class String provides static methods that
take an argument of any type and convert it to a String object. Figure 14.9 demonstrates
the String class valueOf methods.
The expression String.valueOf(charArray) at line 18 uses the character array char-
Array to create a new String object. The expression String.valueOf(charArray, 3, 3)
at line 20 uses a portion of the character array charArray to create a new String object.
The second argument specifies the starting index from which the characters are used. The
third argument specifies the number of characters to be used.
1
// Fig. 14.9: StringValueOf.java
2
// String valueOf methods.
3
4
public class StringValueOf
5
{
6
public static void main(String[] args)
7
{
8
char [] charArray = { 'a' , 'b' , 'c' , 'd' , 'e' , 'f' };
9
boolean booleanValue = true ;
10
char characterValue = 'Z' ;
11
int integerValue = 7 ;
12
long longValue = 10000000000L ; // L suffix indicates long
float floatValue = 2.5f ; // f indicates that 2.5 is a float
13
14
double doubleValue = 33.333 ; // no suffix, double is default
15
Object objectRef = "hello" ; // assign string to an Object reference
16
17
System.out.printf(
18
"char array = %s%n" ,
String.valueOf(charArray)
);
19
System.out.printf( "part of char array = %s%n" ,
20
String.valueOf(charArray, 3 , 3 )
);
21
System.out.printf(
22
"boolean = %s%n" ,
String.valueOf(booleanValue)
);
23
System.out.printf(
24
"char = %s%n" ,
String.valueOf(characterValue)
);
Fig. 14.9 | String valueOf methods. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search