Java Reference
In-Depth Information
Line 12 instantiates a new String using class String 's no-argument constructor and
assigns its reference to s1 . The new String object contains no characters (i.e., the empty
string , which can also be represented as "" ) and has a length of 0. Line 13 instantiates a
new String object using class String 's constructor that takes a String object as an argu-
ment and assigns its reference to s2 . The new String object contains the same sequence
of characters as the String object s that's passed as an argument to the constructor.
Performance Tip 14.2
It's not necessary to copy an existing String object. String objects are immutable, because
class String does not provide methods that allow the contents of a String object to be
modified after it is created.
Line 14 instantiates a new String object and assigns its reference to s3 using class
String 's constructor that takes a char array as an argument. The new String object con-
tains a copy of the characters in the array.
Line 15 instantiates a new String object and assigns its reference to s4 using class
String 's constructor that takes a char array and two integers as arguments. The second
argument specifies the starting position (the offset ) from which characters in the array are
accessed. Remember that the first character is at position 0 . The third argument specifies
the number of characters (the count) to access in the array. The new String object is
formed from the accessed characters. If the offset or the count specified as an argument
results in accessing an element outside the bounds of the character array, a StringIndex-
OutOfBoundsException is thrown.
14.3.2 String Methods length , charAt and getChars
String methods length , charAt and getChars return the length of a String , obtain the
character at a specific location in a String and retrieve a set of characters from a String
as a char array, respectively. Figure 14.2 demonstrates each of these methods.
1
// Fig. 14.2: StringMiscellaneous.java
2
// This application demonstrates the length, charAt and getChars
3
// methods of the String class.
4
5
public class StringMiscellaneous
6
{
7
public static void main(String[] args)
8
{
9
String s1 = "hello there" ;
10
char [] charArray = new char[ 5 ];
11
12
System.out.printf( "s1: %s" , s1);
13
14
// test length method
15
System.out.printf( "%nLength of s1: %d" ,
s1.length()
);
16
17
// loop through characters in s1 with charAt and display reversed
18
System.out.printf( "%nThe string reversed is: " );
Fig. 14.2 | String methods length , charAt and getChars . (Part 1 of 2.)
 
 
Search WWH ::




Custom Search