{"id":3463,"date":"2019-06-20T11:45:57","date_gmt":"2019-06-20T11:45:57","guid":{"rendered":"http:\/\/softlect.in\/?p=3463"},"modified":"2019-06-20T12:03:35","modified_gmt":"2019-06-20T12:03:35","slug":"java-string-handling","status":"publish","type":"post","link":"http:\/\/softlect.com\/index.php\/java-string-handling\/","title":{"rendered":"Java String Handling"},"content":{"rendered":"<h1>String Handling<\/h1>\n<p>&nbsp;<\/p>\n<p>In Java a <em>string <\/em>is a sequence of characters. Java implements strings as objects of type <strong>String<\/strong>. For example, Java has methods to compare two strings, search for a substring, concatenate two strings, and change the case of letters within a string. Also, <strong>String <\/strong>objects can be constructed a number of ways. Somewhat unexpectedly, when you create a <strong>String <\/strong>object, you are creating a string that cannot be changed. That is, once a <strong>String <\/strong>object has been created, you cannot change the characters that comprise that string. You can still perform all types of string operations. The difference is that each time you need an altered version of an existing string; a new <strong>String <\/strong>object is created that contains the modifications. For those cases in which a modifiable string is desired, there is a companion class to <strong>String <\/strong>called <strong>StringBuffer<\/strong>, whose objects contain strings that can be modified after they are created. Both the <strong>String <\/strong>and <strong>StringBuffer <\/strong>classes are defined in <strong>java.lang<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<h2>The String Constructors<\/h2>\n<p>The <strong>String <\/strong>class supports several constructors. To create an empty <strong>String<\/strong>, you call the default constructor. For example,<\/p>\n<p>String s = new String();<\/p>\n<p>&nbsp;<\/p>\n<p>Will create an instance of <strong>String <\/strong>with no characters in it. Frequently, you will want to create strings that have initial values. To create a <strong>String <\/strong>initialized by an array of characters, use the constructor shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>String(char <em>chars<\/em>[ ])<\/p>\n<p>&nbsp;<\/p>\n<p>Here is an example:<\/p>\n<p>&nbsp;<\/p>\n<p>char chars[] = { &#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217; };<\/p>\n<p>String s = new String(chars);<\/p>\n<p>&nbsp;<\/p>\n<p>This constructor initializes <strong>s <\/strong>with the string \u201cabc\u201d. You can specify a subrange of a character array as an initializer using the following constructor:<\/p>\n<p>&nbsp;<\/p>\n<p>String(char <em>chars<\/em>[ ], int <em>startIndex<\/em>, int <em>numChars<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>startIndex <\/em>specifies the index at which the sub range begins, and <em>numChars <\/em>specifies the number of characters to use. Here is an example:<\/p>\n<p>&nbsp;<\/p>\n<p>char chars[] = { &#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;, &#8216;d&#8217;, &#8216;e&#8217;, &#8216;f&#8217; };<\/p>\n<p>String s = new String(chars, 2, 3);<\/p>\n<p>&nbsp;<\/p>\n<p>This initializes <strong>s <\/strong>with the characters <strong>cde<\/strong>. You can construct a <strong>String <\/strong>object that contains the same character sequence as another <strong>String <\/strong>object using this constructor:<\/p>\n<p>&nbsp;<\/p>\n<p>String(String <em>strObj<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>strObj <\/em>is a <strong>String <\/strong>object. Consider this example:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Construct one String from another.<\/p>\n<p>class MakeString {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>char c[] = {&#8216;J&#8217;, &#8216;a&#8217;, &#8216;v&#8217;, &#8216;a&#8217;};<\/p>\n<p>String s1 = new String(c);<\/p>\n<p>String s2 = new String(s1);<\/p>\n<p>System.out.println(s1);<\/p>\n<p>System.out.println(s2);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output from this program is as follows:<\/p>\n<p>Java<\/p>\n<p>Java<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, <strong>s1 <\/strong>and <strong>s2 <\/strong>contain the same string. The <strong>String <\/strong>class provides constructors that initialize a string when given a <strong>byte <\/strong>array. Their forms are shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>String(byte <em>asciiChars<\/em>[ ])<\/p>\n<p>String(byte <em>asciiChars<\/em>[ ], int <em>startIndex<\/em>, int <em>numChars<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>asciiChars <\/em>specifies the array of bytes. The second form allows you to specify a subrange. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. The following program illustrates these constructors:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Construct string from subset of char array.<\/p>\n<p>class SubStringCons {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>byte ascii[] = {65, 66, 67, 68, 69, 70 };<\/p>\n<p>String s1 = new String(ascii);<\/p>\n<p>System.out.println(s1);<\/p>\n<p>String s2 = new String(ascii, 2, 3);<\/p>\n<p>System.out.println(s2);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>This program generates the following output:<\/p>\n<p>ABCDEF<\/p>\n<p>CDE<\/p>\n<p>&nbsp;<\/p>\n<p>Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters. However, most of the time, you will want to use the default encoding provided by the platform.<\/p>\n<p>&nbsp;<\/p>\n<h3>String Length<\/h3>\n<p>The length of a string is the number of characters that it contains. To obtain this value, call the <strong>length( ) <\/strong>method, shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>int length( )<\/p>\n<p>&nbsp;<\/p>\n<p>The following fragment prints \u201c3\u201d, since there are three characters in the string <strong>s<\/strong>:<\/p>\n<p>char chars[] = { &#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217; };<\/p>\n<p>String s = new String(chars);<\/p>\n<p>System.out.println(s.length());<\/p>\n<p>&nbsp;<\/p>\n<h2>Special String Operations<\/h2>\n<p>&nbsp;<\/p>\n<p>Java has added special support for several string operations within the syntax of the language. These operations include the automatic creation of new <strong>String <\/strong>instances from string literals, concatenation of multiple <strong>String <\/strong>objects by use of the <strong>+ <\/strong>operator, and the conversion of other data types to a string representation. There are explicit methods available to perform all of these functions.<\/p>\n<p>&nbsp;<\/p>\n<h3>String Literals<\/h3>\n<p>The earlier examples showed how to explicitly create a <strong>String <\/strong>instance from an array of characters by using the <strong>new <\/strong>operator. However, there is an easier way to do this using a string literal. For each string literal in your program, Java automatically constructs a <strong>String <\/strong>object. Thus, you can use a string literal to initialize a <strong>String <\/strong>object. For example, the following code fragment creates two equivalent strings:<\/p>\n<p>&nbsp;<\/p>\n<p>char chars[] = { &#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217; };<\/p>\n<p>String s1 = new String(chars);<\/p>\n<p>String s2 = &#8220;abc&#8221;; \/\/ use string literal<\/p>\n<p>&nbsp;<\/p>\n<p>Because a <strong>String <\/strong>object is created for every string literal, you can use a string literal any place you can use a <strong>String <\/strong>object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the <strong>length( ) <\/strong>method on the string \u201cabc\u201d. As expected, it prints \u201c3\u201d<\/p>\n<p>&nbsp;<\/p>\n<p>System.out.println(&#8220;abc&#8221;.length());<\/p>\n<p>&nbsp;<\/p>\n<h3>String Concatenation<\/h3>\n<p>In general, Java does not allow operators to be applied to <strong>String <\/strong>objects. The one exception to this rule is the <strong>+ <\/strong>operator, which concatenates two strings, producing a <strong>String <\/strong>object as the result. This allows you to chain together a series of <strong>+ <\/strong>operations. For example, the following fragment concatenates three strings:<\/p>\n<p>&nbsp;<\/p>\n<p>String age = &#8220;9&#8221;;<\/p>\n<p>String s = &#8220;He is &#8221; + age + &#8221; years old.&#8221;;<\/p>\n<p>System.out.println(s);<\/p>\n<p>&nbsp;<\/p>\n<p>This displays the string \u201cHe is 9 years old.\u201d Here is another an example:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Using concatenation to prevent long lines.<\/p>\n<p>class ConCat {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>String longStr = &#8220;This could have been &#8221; +<\/p>\n<p>&#8220;a very long line that would have &#8221; +<\/p>\n<p>&#8220;wrapped around. But string concatenation &#8221; +<\/p>\n<p>&#8220;prevents this.&#8221;;<\/p>\n<p>System.out.println(longStr);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<h3>String Concatenation with Other Data Types<\/h3>\n<p>You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example:<\/p>\n<p>&nbsp;<\/p>\n<p>int age = 9;<\/p>\n<p>String s = &#8220;He is &#8221; + age + &#8221; years old.&#8221;;<\/p>\n<p>System.out.println(s);<\/p>\n<p>&nbsp;<\/p>\n<p>In this case, <strong>age <\/strong>is an <strong>int <\/strong>rather than another <strong>String<\/strong>, but the output produced is the same as before. This is because the <strong>int <\/strong>value in <strong>age <\/strong>is automatically converted into its string representation within a <strong>String <\/strong>object. This string is then concatenated as before. The compiler will convert an operand to its string equivalent whenever the other operand of the <strong>+ <\/strong>is an instance of <strong>String<\/strong>. Be careful when you mix other types of operations with string concatenation expressions, however. You might get surprising results. Consider the following:<\/p>\n<p>&nbsp;<\/p>\n<p>String s = &#8220;four: &#8221; + 2 + 2;<\/p>\n<p>System.out.println(s);<\/p>\n<p>&nbsp;<\/p>\n<p>This fragment displays four: 22<\/p>\n<p>rather than the four: 4<\/p>\n<p>&nbsp;<\/p>\n<p>Operator precedence causes the concatenation of \u201cfour\u201d with the string equivalent of 2 to take place first. This result is then concatenated with the string equivalent of 2 a second time. To complete the integer addition first, you must use parentheses, like this:<\/p>\n<p>&nbsp;<\/p>\n<p>String s = &#8220;four: &#8221; + (2 + 2);<\/p>\n<p>&nbsp;<\/p>\n<p>Now <strong>s <\/strong>contains the string \u201cfour: 4\u201d.<\/p>\n<p>&nbsp;<\/p>\n<h3>String Conversion and toString( )<\/h3>\n<p>When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method <strong>valueOf( ) <\/strong>defined by <strong>String<\/strong>. <strong>valueOf( ) <\/strong>is overloaded for all the simple types and for type <strong>Object<\/strong>. For the simple types, <strong>valueOf( ) <\/strong>returns a string that contains the human-readable equivalent of the value with which it is called. For objects, <strong>valueOf( ) <\/strong>calls the <strong>toString( ) <\/strong>method on the object. Here, let\u2019s examine the <strong>toString( ) <\/strong>method, because it is the means by which you can determine the string representation for objects of classes that you create. Every class implements <strong>toString( ) <\/strong>because it is defined by <strong>Object<\/strong>. Fortunately, this is easy to do. The <strong>toString( ) <\/strong>method has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>String toString( )<\/p>\n<p>&nbsp;<\/p>\n<p>To implement <strong>toString( )<\/strong>, simply return a <strong>String <\/strong>object that contains the humanreadable string that appropriately describes an object of your class. By overriding <strong>toString( ) <\/strong>for classes that you create, you allow them to be fully integrated into Java\u2019s programming environment. For example, they can be used in <strong>print( ) <\/strong>and <strong>println( ) <\/strong>statements and in concatenation expressions. The following program demonstrates this by overriding <strong>toString( ) <\/strong>for the <strong>Box <\/strong>class:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Override toString() for Box class.<\/p>\n<p>class Box {<\/p>\n<p>double width;<\/p>\n<p>double height;<\/p>\n<p>double depth;<\/p>\n<p>Box(double w, double h, double d) {<\/p>\n<p>width = w;<\/p>\n<p>height = h;<\/p>\n<p>depth = d;<\/p>\n<p>}<\/p>\n<p>public String toString() {<\/p>\n<p>return &#8220;Dimensions are &#8221; + width + &#8221; by &#8221; +<\/p>\n<p>depth + &#8221; by &#8221; + height + &#8220;.&#8221;;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class toStringDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Box b = new Box(10, 12, 14);<\/p>\n<p>String s = &#8220;Box b: &#8221; + b; \/\/ concatenate Box object<\/p>\n<p>System.out.println(b); \/\/ convert Box to string<\/p>\n<p>System.out.println(s);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output of this program is shown here:<\/p>\n<p>Dimensions are 10.0 by 14.0 by 12.0<\/p>\n<p>Box b: Dimensions are 10.0 by 14.0 by 12.0<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, <strong>Box<\/strong>\u2019s <strong>toString( ) <\/strong>method is automatically invoked when a <strong>Box <\/strong>object is used in a concatenation expression or in a call to <strong>println( )<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<h2>Character Extraction<\/h2>\n<p>The <strong>String <\/strong>class provides a number of ways in which characters can be extracted from a <strong>String <\/strong>object. Each is examined here. Although the characters that comprise a string within a <strong>String <\/strong>object cannot be indexed as if they were a character array, many of the <strong>String <\/strong>methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero.<\/p>\n<p>&nbsp;<\/p>\n<h3>charAt( )<\/h3>\n<p>To extract a single character from a <strong>String<\/strong>, you can refer directly to an individual character via the <strong>charAt() <\/strong>method. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>char charAt(int <em>where<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>where <\/em>is the index of the character that you want to obtain. The value of <em>where <\/em>must be nonnegative and specify a location within the string. <strong>charAt( ) <\/strong>returns the character at the specified location. For example,<\/p>\n<p>&nbsp;<\/p>\n<p>char ch;<\/p>\n<p>ch = &#8220;abc&#8221;.charAt(1);<\/p>\n<p>&nbsp;<\/p>\n<p>assigns the value \u201c<strong>b<\/strong>\u201d to <strong>ch<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<h3>getChars( )<\/h3>\n<p>If you need to extract more than one character at a time, you can use the <strong>getChars( ) <\/strong>method. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>void getChars(int <em>sourceStart<\/em>, int <em>sourceEnd<\/em>, char <em>target<\/em>[ ], int <em>targetStart<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>sourceStart <\/em>specifies the index of the beginning of the substring, and <em>sourceEnd <\/em>specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from <em>sourceStart <\/em>through <em>sourceEnd<\/em>\u20131. The array that will receive the characters is specified by <em>target. <\/em>The index within <em>target <\/em>at which the substring will be copied is passed in <em>targetStart. <\/em>Care must be taken to assure that the <em>target <\/em>array is large enough to hold the number of characters in the specified substring. The following program demonstrates <strong>getChars( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">class getCharsDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>String s = &#8220;This is a demo of the getChars method.&#8221;;<\/p>\n<p>int start = 10;<\/p>\n<p>int end = 14;<\/p>\n<p>char buf[] = new char[end &#8211; start];<\/p>\n<p>s.getChars(start, end, buf, 0);<\/p>\n<p>System.out.println(buf);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Here is the output of this program:<\/p>\n<p>demo<\/p>\n<p>&nbsp;<\/p>\n<h3>getBytes( )<\/h3>\n<p>There is an alternative to <strong>getChars( ) <\/strong>that stores the characters in an array of bytes. This method is called <strong>getBytes( )<\/strong>, and it uses the default character-to-byte conversions provided by the platform. Here is its simplest form:<\/p>\n<p>&nbsp;<\/p>\n<p>byte[ ] getBytes( )<\/p>\n<p>&nbsp;<\/p>\n<p>Other forms of <strong>getBytes( ) <\/strong>are also available. <strong>getBytes( ) <\/strong>is most useful when you are exporting a <strong>String <\/strong>value into an environment that does not support 16-bit Unicode characters.<\/p>\n<p>&nbsp;<\/p>\n<h3>toCharArray( )<\/h3>\n<p>If you want to convert all the characters in a <strong>String <\/strong>object into a character array, the easiest way is to call <strong>toCharArray( )<\/strong>. It returns an array of characters for the entire string. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>char[ ] toCharArray( )<\/p>\n<p>&nbsp;<\/p>\n<p>This function is provided as a convenience, since it is possible to use <strong>getChars( ) <\/strong>to achieve the same result.<\/p>\n<p>&nbsp;<\/p>\n<h2>String Comparison<\/h2>\n<p>The <strong>String <\/strong>class includes several methods that compare strings or substrings within strings. Each is examined here.<\/p>\n<p>&nbsp;<\/p>\n<h3>equals( ) and equalsIgnoreCase( )<\/h3>\n<p>To compare two strings for equality, use <strong>equals( )<\/strong>. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>boolean equals(Object <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>str <\/em>is the <strong>String <\/strong>object being compared with the invoking <strong>String <\/strong>object. It returns <strong>true <\/strong>if the strings contain the same characters in the same order, and <strong>false <\/strong>otherwise. The comparison is case-sensitive. To perform a comparison that ignores case differences, call <strong>equalsIgnoreCase( )<\/strong>. When it compares two strings, it considers <strong>A-Z <\/strong>to be the same as <strong>a-z<\/strong>. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>boolean equalsIgnoreCase(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>str <\/em>is the <strong>String <\/strong>object being compared with the invoking <strong>String <\/strong>object. It, too, returns <strong>true <\/strong>if the strings contain the same characters in the same order, and <strong>false <\/strong>otherwise. Here is an example that demonstrates <strong>equals( ) <\/strong>and <strong>equalsIgnoreCase( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate equals() and equalsIgnoreCase().<\/p>\n<p>class equalsDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>String s1 = &#8220;Hello&#8221;;<\/p>\n<p>String s2 = &#8220;Hello&#8221;;<\/p>\n<p>String s3 = &#8220;Good-bye&#8221;;<\/p>\n<p>String s4 = &#8220;HELLO&#8221;;<\/p>\n<p>System.out.println(s1 + &#8221; equals &#8221; + s2 + &#8221; -&gt; &#8221; +<\/p>\n<p>s1.equals(s2));<\/p>\n<p>System.out.println(s1 + &#8221; equals &#8221; + s3 + &#8221; -&gt; &#8221; +<\/p>\n<p>s1.equals(s3));<\/p>\n<p>System.out.println(s1 + &#8221; equals &#8221; + s4 + &#8221; -&gt; &#8221; +<\/p>\n<p>s1.equals(s4));<\/p>\n<p>System.out.println(s1 + &#8221; equalsIgnoreCase &#8221; + s4 + &#8221; -&gt; &#8221; +<\/p>\n<p>s1.equalsIgnoreCase(s4));<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output from the program is shown here:<\/p>\n<p>Hello equals Hello -&gt; true<\/p>\n<p>Hello equals Good-bye -&gt; false<\/p>\n<p>Hello equals HELLO -&gt; false<\/p>\n<p>Hello equalsIgnoreCase HELLO -&gt; true<\/p>\n<p>&nbsp;<\/p>\n<h3>regionMatches( )<\/h3>\n<p>The <strong>regionMatches( ) <\/strong>method compares a specific region inside a string with another specific region in another string. There is an overloaded form that allows you to ignore case in such comparisons. Here are the general forms for these two methods:<\/p>\n<p>&nbsp;<\/p>\n<p>boolean regionMatches(int s<em>tartIndex<\/em>, String <em>str2<\/em>,<\/p>\n<p>int <em>str2StartIndex<\/em>, int <em>numChars<\/em>)<\/p>\n<p>boolean regionMatches(boolean <em>ignoreCase<\/em>,<\/p>\n<p>int <em>startIndex<\/em>, String <em>str2<\/em>,<\/p>\n<p>int <em>str2StartIndex<\/em>, int <em>numChars<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>For both versions, <em>startIndex <\/em>specifies the index at which the region begins within the invoking <strong>String <\/strong>object. The <strong>String <\/strong>being compared is specified by <em>str2<\/em>. The index at which the comparison will start within <em>str2 <\/em>is specified by <em>str2StartIndex<\/em>. The length of the substring being compared is passed in <em>numChars<\/em>. In the second version, if <em>ignoreCase <\/em>is <strong>true<\/strong>, the case of the characters is ignored. Otherwise, case is significant.<\/p>\n<p>&nbsp;<\/p>\n<h3>startsWith( ) and endsWith( )<\/h3>\n<p><strong>String <\/strong>defines two routines that are, more or less, specialized forms of <strong>regionMatches( )<\/strong>. The <strong>startsWith( ) <\/strong>method determines whether a given <strong>String <\/strong>begins with a specified string. Conversely, <strong>endsWith( ) <\/strong>determines whether the <strong>String <\/strong>in question ends with a specified string. They have the following general forms:<\/p>\n<p>&nbsp;<\/p>\n<p>boolean startsWith(String <em>str<\/em>)<\/p>\n<p>boolean endsWith(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>str <\/em>is the <strong>String <\/strong>being tested. If the string matches, <strong>true <\/strong>is returned. Otherwise, <strong>false <\/strong>is returned. For example,<\/p>\n<p>&nbsp;<\/p>\n<p>&#8220;Foobar&#8221;.endsWith(&#8220;bar&#8221;)<\/p>\n<p>and<\/p>\n<p>&#8220;Foobar&#8221;.startsWith(&#8220;Foo&#8221;)<\/p>\n<p>are both <strong>true<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<p>A second form of <strong>startsWith( )<\/strong>, shown here, lets you specify a starting point:<\/p>\n<p>&nbsp;<\/p>\n<p>boolean startsWith(String s<em>tr<\/em>, int <em>startIndex<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>startIndex <\/em>specifies the index into the invoking string at which point the search will begin. For example,<\/p>\n<p>&#8220;Foobar&#8221;.startsWith(&#8220;bar&#8221;, 3)<\/p>\n<p>&nbsp;<\/p>\n<p>returns <strong>true<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<h3>equals( ) Versus ==<\/h3>\n<p>It is important to understand that the <strong>equals( ) <\/strong>method and the <strong>== <\/strong>operator perform two different operations. As just explained, the <strong>equals( ) <\/strong>method compares the characters inside a <strong>String <\/strong>object. The <strong>== <\/strong>operator compares two object references to see whether they refer to the same instance. The following program shows how two different <strong>String <\/strong>objects can contain the same characters, but references to these objects will not compare as equal:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ equals() vs ==<\/p>\n<p>class EqualsNotEqualTo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>String s1 = &#8220;Hello&#8221;;<\/p>\n<p>String s2 = new String(s1);<\/p>\n<p>System.out.println(s1 + &#8221; equals &#8221; + s2 + &#8221; -&gt; &#8221; +<\/p>\n<p>s1.equals(s2));<\/p>\n<p>System.out.println(s1 + &#8221; == &#8221; + s2 + &#8221; -&gt; &#8221; + (s1 == s2));<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The variable <strong>s1 <\/strong>refers to the <strong>String <\/strong>instance created by \u201c<strong>Hello<\/strong>\u201d. The object referred to by <strong>s2 <\/strong>is created with <strong>s1 <\/strong>as an initializer. Thus, the contents of the two <strong>String <\/strong>objects are identical, but they are distinct objects. This means that <strong>s1 <\/strong>and <strong>s2 <\/strong>do not refer to the same objects and are, therefore, not <strong>==<\/strong>, as is shown here by the output of the preceding example:<\/p>\n<p>&nbsp;<\/p>\n<p>Hello equals Hello -&gt; true<\/p>\n<p>Hello == Hello -&gt; false<\/p>\n<p>&nbsp;<\/p>\n<h3>compareTo( )<\/h3>\n<p>Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is <em>less than, equal to, <\/em>or <em>greater than <\/em>the next. A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The <strong>String <\/strong>method <strong>compareTo( ) <\/strong>serves this purpose. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>int compareTo(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>str <\/em>is the <strong>String <\/strong>being compared with the invoking <strong>String<\/strong>. The result of the comparison is returned and is interpreted as shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>Value Meaning<\/p>\n<p>Less than zero \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0The invoking string is less than <em>str.<\/em><\/p>\n<p>Greater than zero \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0The invoking string is greater than <em>str.<\/em><\/p>\n<p>Zero \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0The two strings are equal.<\/p>\n<p>&nbsp;<\/p>\n<p>Here is a sample program that sorts an array of strings. The program uses <strong>compareTo( ) <\/strong>to determine sort ordering for a bubble sort:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ A bubble sort for Strings.<\/p>\n<p>class SortString {<\/p>\n<p>static String arr[] = {<\/p>\n<p>&#8220;Now&#8221;, &#8220;is&#8221;, &#8220;the&#8221;, &#8220;time&#8221;, &#8220;for&#8221;, &#8220;all&#8221;, &#8220;good&#8221;, &#8220;men&#8221;,<\/p>\n<p>&#8220;to&#8221;, &#8220;come&#8221;, &#8220;to&#8221;, &#8220;the&#8221;, &#8220;aid&#8221;, &#8220;of&#8221;, &#8220;their&#8221;, &#8220;country&#8221;<\/p>\n<p>};<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>for(int j = 0; j &lt; arr.length; j++) {<\/p>\n<p>for(int i = j + 1; i &lt; arr.length; i++) {<\/p>\n<p>if(arr[i].compareTo(arr[j]) &lt; 0) {<\/p>\n<p>String t = arr[j];<\/p>\n<p>arr[j] = arr[i];<\/p>\n<p>arr[i] = t;<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>System.out.println(arr[j]);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output of this program is the list of words:<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">Now<\/p>\n<p>aid<\/p>\n<p>all<\/p>\n<p>come<\/p>\n<p>country<\/p>\n<p>for<\/p>\n<p>good<\/p>\n<p>is<\/p>\n<p>men<\/p>\n<p>of<\/p>\n<p>the<\/p>\n<p>the<\/p>\n<p>their<\/p>\n<p>time<\/p>\n<p>to<\/p>\n<p>to<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>As you can see from the output of this example, <strong>compareTo( ) <\/strong>takes into account uppercase and lowercase letters. The word \u201cNow\u201d came out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set. If you want to ignore case differences when comparing two strings, use <strong>compareToIgnoreCase( )<\/strong>, shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>int compareToIgnoreCase(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>This method returns the same results as <strong>compareTo( )<\/strong>, except that case differences are ignored. This method was added by Java 2. You might want to try substituting it into the previous program. After doing so, \u201cNow\u201d will no longer be first.<\/p>\n<p>&nbsp;<\/p>\n<h2>Searching Strings<\/h2>\n<p>&nbsp;<\/p>\n<p>The <strong>String <\/strong>class provides two methods that allow you to search a string for a specified character or substring:<\/p>\n<p>&nbsp;<\/p>\n<p><strong>indexOf( ) <\/strong>Searches for the first occurrence of a character or substring.<\/p>\n<p><strong>lastIndexOf( ) <\/strong>Searches for the last occurrence of a character or substring.<\/p>\n<p>&nbsp;<\/p>\n<p>These two methods are overloaded in several different ways. In all cases, the methods return the index at which the character or substring was found, or \u20131 on failure. To search for the first occurrence of a character, use<\/p>\n<p>&nbsp;<\/p>\n<p>int indexOf(int <em>ch<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>To search for the last occurrence of a character, use<\/p>\n<p>int lastIndexOf(int <em>ch<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>ch <\/em>is the character being sought. To search for the first or last occurrence of a substring, use<\/p>\n<p>&nbsp;<\/p>\n<p>int indexOf(String <em>str<\/em>)<\/p>\n<p>int lastIndexOf(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>str <\/em>specifies the substring. You can specify a starting point for the search using these forms:<\/p>\n<p>&nbsp;<\/p>\n<p>int indexOf(int <em>ch<\/em>, int <em>startIndex<\/em>)<\/p>\n<p>int lastIndexOf(int <em>ch<\/em>, int <em>startIndex<\/em>)<\/p>\n<p>int indexOf(String <em>str<\/em>, int <em>startIndex<\/em>)<\/p>\n<p>int lastIndexOf(String <em>str<\/em>, int <em>startIndex<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>startIndex <\/em>specifies the index at which point the search begins. For <strong>indexOf( )<\/strong>, the search runs from <em>startIndex <\/em>to the end of the string. For <strong>lastIndexOf( )<\/strong>, the search runs from <em>startIndex <\/em>to zero. The following example shows how to use the various index methods to search inside of <strong>String<\/strong>s:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate indexOf() and lastIndexOf().<\/p>\n<p>class indexOfDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>String s = &#8220;Now is the time for all good men &#8221; +<\/p>\n<p>&#8220;to come to the aid of their country.&#8221;;<\/p>\n<p>System.out.println(s);<\/p>\n<p>System.out.println(&#8220;indexOf(t) = &#8221; +<\/p>\n<p>s.indexOf(&#8216;t&#8217;));<\/p>\n<p>System.out.println(&#8220;lastIndexOf(t) = &#8221; +<\/p>\n<p>s.lastIndexOf(&#8216;t&#8217;));<\/p>\n<p>System.out.println(&#8220;indexOf(the) = &#8221; +<\/p>\n<p>s.indexOf(&#8220;the&#8221;));<\/p>\n<p>System.out.println(&#8220;lastIndexOf(the) = &#8221; +<\/p>\n<p>s.lastIndexOf(&#8220;the&#8221;));<\/p>\n<p>System.out.println(&#8220;indexOf(t, 10) = &#8221; +<\/p>\n<p>s.indexOf(&#8216;t&#8217;, 10));<\/p>\n<p>System.out.println(&#8220;lastIndexOf(t, 60) = &#8221; +<\/p>\n<p>s.lastIndexOf(&#8216;t&#8217;, 60));<\/p>\n<p>System.out.println(&#8220;indexOf(the, 10) = &#8221; +<\/p>\n<p>s.indexOf(&#8220;the&#8221;, 10));<\/p>\n<p>System.out.println(&#8220;lastIndexOf(the, 60) = &#8221; +<\/p>\n<p>s.lastIndexOf(&#8220;the&#8221;, 60));<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Here is the output of this program:<\/p>\n<p>Now is the time for all good men to come to the aid of their country.<\/p>\n<p>indexOf(t) = 7<\/p>\n<p>lastIndexOf(t) = 65<\/p>\n<p>indexOf(the) = 7<\/p>\n<p>lastIndexOf(the) = 55<\/p>\n<p>indexOf(t, 10) = 11<\/p>\n<p>lastIndexOf(t, 60) = 55<\/p>\n<p>indexOf(the, 10) = 44<\/p>\n<p>lastIndexOf(the, 60) = 55<\/p>\n<p>&nbsp;<\/p>\n<h2>Modifying a String<\/h2>\n<p>Because <strong>String <\/strong>objects are immutable, whenever you want to modify a <strong>String<\/strong>, you must either copy it into a <strong>StringBuffer <\/strong>or use one of the following <strong>String <\/strong>methods, which will construct a new copy of the string with your modifications complete.<\/p>\n<p>&nbsp;<\/p>\n<h3>substring( )<\/h3>\n<p>You can extract a substring using <strong>substring( )<\/strong>. It has two forms. The first is String substring(int <em>startIndex<\/em>) Here, <em>startIndex <\/em>specifies the index at which the substring will begin. This form returns a copy of the substring that begins at <em>startIndex <\/em>and runs to the end of the invoking string. The second form of <strong>substring( ) <\/strong>allows you to specify both the beginning and ending index of the substring:<\/p>\n<p>&nbsp;<\/p>\n<p>String substring(int <em>startIndex<\/em>, int <em>endIndex<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>startIndex <\/em>specifies the beginning index, and <em>endIndex <\/em>specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index. The following program uses <strong>substring( ) <\/strong>to replace all instances of one substring with another within a string:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Substring replacement.<\/p>\n<p>class StringReplace {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>String org = &#8220;This is a test. This is, too.&#8221;;<\/p>\n<p>String search = &#8220;is&#8221;;<\/p>\n<p>String sub = &#8220;was&#8221;;<\/p>\n<p>String result = &#8220;&#8221;;<\/p>\n<p>int i;<\/p>\n<p>do { \/\/ replace all matching substrings<\/p>\n<p>System.out.println(org);<\/p>\n<p>i = org.indexOf(search);<\/p>\n<p>if(i != -1) {<\/p>\n<p>result = org.substring(0, i);<\/p>\n<p>result = result + sub;<\/p>\n<p>result = result + org.substring(i + search.length());<\/p>\n<p>org = result;<\/p>\n<p>}<\/p>\n<p>} while(i != -1);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output from this program is shown here:<\/p>\n<p>This is a test. This is, too.<\/p>\n<p>Thwas is a test. This is, too.<\/p>\n<p>Thwas was a test. This is, too.<\/p>\n<p>Thwas was a test. Thwas is, too.<\/p>\n<p>Thwas was a test. Thwas was, too.<\/p>\n<p>&nbsp;<\/p>\n<h3>concat( )<\/h3>\n<p>You can concatenate two strings using <strong>concat( )<\/strong>, shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>String concat(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>This method creates a new object that contains the invoking string with the contents of <em>str <\/em>appended to the end. <strong>concat( ) <\/strong>performs the same function as <strong>+<\/strong>. For example,<\/p>\n<p>&nbsp;<\/p>\n<p>String s1 = &#8220;one&#8221;;<\/p>\n<p>String s2 = s1.concat(&#8220;two&#8221;);<\/p>\n<p>puts the string \u201conetwo\u201d into <strong>s2<\/strong>. It generates the same result as the following sequence:<\/p>\n<p>String s1 = &#8220;one&#8221;;<\/p>\n<p>String s2 = s1 + &#8220;two&#8221;;<\/p>\n<p>&nbsp;<\/p>\n<h3>replace( )<\/h3>\n<p>The <strong>replace( ) <\/strong>method replaces all occurrences of one character in the invoking string with another character. It has the following general form:<\/p>\n<p>&nbsp;<\/p>\n<p>String replace(char <em>original<\/em>, char <em>replacement<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>original <\/em>specifies the character to be replaced by the character specified by <em>replacement. <\/em>The resulting string is returned. For example,<\/p>\n<p>&nbsp;<\/p>\n<p>String s = &#8220;Hello&#8221;.replace(&#8216;l&#8217;, &#8216;w&#8217;);<\/p>\n<p>puts the string \u201cHewwo\u201d into <strong>s<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<h3>trim( )<\/h3>\n<p>The <strong>trim( ) <\/strong>method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>String trim( )<\/p>\n<p>&nbsp;<\/p>\n<p>Here is an example:<\/p>\n<p>String s = &#8221; Hello World &#8220;.trim();<\/p>\n<p>&nbsp;<\/p>\n<p>This puts the string \u201cHello World\u201d into <strong>s<\/strong>. The <strong>trim( ) <\/strong>method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state\u2019s capital. It uses <strong>trim( ) <\/strong>to remove any leading or trailing whitespace that may have inadvertently been entered by the user.<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Using trim() to process commands.<\/p>\n<p>import java.io.*;<\/p>\n<p>class UseTrim {<\/p>\n<p>public static void main(String args[])<\/p>\n<p>throws IOException<\/p>\n<p>{<\/p>\n<p>\/\/ create a BufferedReader using System.in<\/p>\n<p>BufferedReader br = new<\/p>\n<p>BufferedReader(new InputStreamReader(System.in));<\/p>\n<p>String str;<\/p>\n<p>System.out.println(&#8220;Enter &#8216;stop&#8217; to quit.&#8221;);<\/p>\n<p>System.out.println(&#8220;Enter State: &#8220;);<\/p>\n<p>do {<\/p>\n<p>str = br.readLine();<\/p>\n<p>str = str.trim(); \/\/ remove whitespace<\/p>\n<p>if(str.equals(&#8220;Illinois&#8221;))<\/p>\n<p>System.out.println(&#8220;Capital is Springfield.&#8221;);<\/p>\n<p>else if(str.equals(&#8220;Missouri&#8221;))<\/p>\n<p>System.out.println(&#8220;Capital is Jefferson City.&#8221;);<\/p>\n<p>else if(str.equals(&#8220;California&#8221;))<\/p>\n<p>System.out.println(&#8220;Capital is Sacramento.&#8221;);<\/p>\n<p>else if(str.equals(&#8220;Washington&#8221;))<\/p>\n<p>System.out.println(&#8220;Capital is Olympia.&#8221;);<\/p>\n<p>\/\/ &#8230;<\/p>\n<p>} while(!str.equals(&#8220;stop&#8221;));<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<h2>Data Conversion Using valueOf( )<\/h2>\n<p>The <strong>valueOf( ) <\/strong>method converts data from its internal format into a human-readable form. It is a static method that is overloaded within <strong>String <\/strong>for all of Java\u2019s built-in types, so that each type can be converted properly into a string. <strong>valueOf( ) <\/strong>is also overloaded for type <strong>Object<\/strong>, so an object of any class type you create can also be used as an argument. (Recall that <strong>Object <\/strong>is a superclass for all classes.) Here are a few of its forms:<\/p>\n<p>&nbsp;<\/p>\n<p>static String valueOf(double <em>num<\/em>)<\/p>\n<p>static String valueOf(long <em>num<\/em>)<\/p>\n<p>static String valueOf(Object <em>ob<\/em>)<\/p>\n<p>static String valueOf(char <em>chars<\/em>[ ])<\/p>\n<p>&nbsp;<\/p>\n<p>As we discussed earlier, <strong>valueOf( ) <\/strong>is called when a string representation of some other type of data is needed for example, during concatenation operations. You can call this method directly with any data type and get a reasonable <strong>String <\/strong>representation. All of the simple types are converted to their common <strong>String <\/strong>representation. Any object that you pass to <strong>valueOf( ) <\/strong>will return the result of a call to the object\u2019s <strong>toString( ) <\/strong>method. In fact, you could just call <strong>toString( ) <\/strong>directly and get the same result. For most arrays, <strong>valueOf( ) <\/strong>returns a rather cryptic string, which indicates that it is an array of some type. For arrays of <strong>char<\/strong>, however, a <strong>String <\/strong>object is created that contains the characters in the <strong>char <\/strong>array. There is a special version of <strong>valueOf( ) <\/strong>that allows you to specify a subset of a <strong>char <\/strong>array. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>static String valueOf(char <em>chars<\/em>[ ], int <em>startIndex<\/em>, int <em>numChars<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>chars <\/em>is the array that holds the characters, <em>startIndex <\/em>is the index into the array of characters at which the desired substring begins, and <em>numChars <\/em>specifies the length of the substring.<\/p>\n<p>&nbsp;<\/p>\n<h2>Changing the Case of Characters Within a String<\/h2>\n<p>The method <strong>toLowerCase( ) <\/strong>converts all the characters in a string from uppercase to lowercase. The <strong>toUpperCase( ) <\/strong>method converts all the characters in a string from lowercase to uppercase. \u00a0Nonalphabetical characters, such as digits, are unaffected. \u00a0Here are the general forms of these methods:<\/p>\n<p>&nbsp;<\/p>\n<p>String toLowerCase( )<\/p>\n<p>String toUpperCase( )<\/p>\n<p>&nbsp;<\/p>\n<p>Both methods return a <strong>String <\/strong>object that contains the uppercase or lowercase equivalent of the invoking <strong>String<\/strong>. Here is an example that uses <strong>toLowerCase( ) <\/strong>and <strong>toUpperCase( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate toUpperCase() and toLowerCase().<\/p>\n<p>class ChangeCase {<\/p>\n<p>public static void main(String args[])<\/p>\n<p>{<\/p>\n<p>String s = &#8220;This is a test.&#8221;;<\/p>\n<p>System.out.println(&#8220;Original: &#8221; + s);<\/p>\n<p>String upper = s.toUpperCase();<\/p>\n<p>String lower = s.toLowerCase();<\/p>\n<p>System.out.println(&#8220;Uppercase: &#8221; + upper);<\/p>\n<p>System.out.println(&#8220;Lowercase: &#8221; + lower);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output produced by the program is shown here:<\/p>\n<p>Original: This is a test.<\/p>\n<p>Uppercase: THIS IS A TEST.<\/p>\n<p>Lowercase: this is a test.<\/p>\n<p>&nbsp;<\/p>\n<h2>String Methods Added by Java 2, Version 1.4<\/h2>\n<p>Java 2, version 1.4 adds several methods to the <strong>String <\/strong>class. These are summarized in the following table.<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"271\">Method<\/td>\n<td width=\"384\">Description<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">boolean contentEquals(StringBuffer <em>str<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Returns <strong>true <\/strong>if the invoking string contains the same string as <em>str<\/em>. Otherwise, returns <strong>false<\/strong>.<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">CharSequence subSequence(int <em>startIndex<\/em>,<\/p>\n<p>int <em>stopIndex<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Returns a substring of the invoking string, beginning at <em>startIndex <\/em>and stopping at <em>stopIndex<\/em>. This method is required by the <strong>CharSequence <\/strong>interface, which is now implemented by <strong>String<\/strong>.<\/p>\n<p>&nbsp;<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">boolean matches(string <em>regExp<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Returns <strong>true <\/strong>if the invoking string matches the regular expression passed in <em>regExp<\/em>. Otherwise, returns <strong>false<\/strong>.<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">String replaceFirst(String <em>regExp<\/em>,<\/p>\n<p>String <em>newStr<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Returns a string in which the first substring that matches the regular expression specified by <em>regExp <\/em>is replaced by <em>newStr<\/em>.<\/p>\n<p>String<\/p>\n<p>&nbsp;<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">replaceAll(String <em>regExp<\/em>, String <em>newStr<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Returns a string in which all substrings that match the regular expression specified by <em>regExp <\/em>are replaced by <em>newStr<\/em>.<\/p>\n<p>&nbsp;<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">String[ ] split(String <em>regExp<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Decomposes the invoking string into parts and returns an array that contains the result. Each part is delimited by the regular expression passed in <em>regExp<\/em>.<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">String[ ] split(String <em>regExp<\/em>, int <em>max<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Decomposes the invoking string into parts and returns an array that contains the result. Each part is delimited by the regular expression passed in <em>regExp<\/em>. The number of pieces is specified by <em>max<\/em>. If <em>max <\/em>is negative, then the invoking string is fully decomposed. Otherwise, if <em>max <\/em>contains a non-zero value, the last entry in the returned array contains the remainder of the invoking string. If <em>max <\/em>is zero, the invoking string is fully decomposed.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h2>StringBuffer<\/h2>\n<p><strong>StringBuffer <\/strong>is a peer class of <strong>String <\/strong>that provides much of the functionality of strings. As you know, <strong>String <\/strong>represents fixed-length, immutable character sequences. In contrast, <strong>StringBuffer <\/strong>represents growable and writeable character sequences. <strong>StringBuffer <\/strong>may have characters and substrings inserted in the middle or appended to the end. <strong>StringBuffer <\/strong>will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with <strong>String <\/strong>and let Java manipulate <strong>StringBuffer<\/strong>s behind the scenes by using the overloaded <strong>+ <\/strong>operator.<\/p>\n<p>&nbsp;<\/p>\n<h3>StringBuffer Constructors<\/h3>\n<p><strong>StringBuffer <\/strong>defines these three constructors:<\/p>\n<p>&nbsp;<\/p>\n<p>StringBuffer( )<\/p>\n<p>StringBuffer(int <em>size<\/em>)<\/p>\n<p>StringBuffer(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a <strong>String <\/strong>argument that sets the initial contents of the <strong>StringBuffer <\/strong>object and reserves room for 16 more characters without reallocation. <strong>StringBuffer <\/strong>allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, <strong>StringBuffer <\/strong>reduces the number of reallocations that take place.<\/p>\n<p>&nbsp;<\/p>\n<h3>length( ) and capacity( )<\/h3>\n<p>The current length of a <strong>StringBuffer <\/strong>can be found via the <strong>length( ) <\/strong>method, while the total allocated capacity can be found through the <strong>capacity( ) <\/strong>method. They have the following general forms:<\/p>\n<p>&nbsp;<\/p>\n<p>int length( )<\/p>\n<p>int capacity( )<\/p>\n<p>&nbsp;<\/p>\n<p>Here is an example:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ StringBuffer length vs. capacity.<\/p>\n<p>class StringBufferDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>StringBuffer sb = new StringBuffer(&#8220;Hello&#8221;);<\/p>\n<p>System.out.println(&#8220;buffer = &#8221; + sb);<\/p>\n<p>System.out.println(&#8220;length = &#8221; + sb.length());<\/p>\n<p>System.out.println(&#8220;capacity = &#8221; + sb.capacity());<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Here is the output of this program, which shows how <strong>StringBuffer <\/strong>reserves extra space for additional manipulations:<\/p>\n<p>buffer = Hello<\/p>\n<p>length = 5<\/p>\n<p>capacity = 21<\/p>\n<p>Since <strong>sb <\/strong>is initialized with the string \u201cHello\u201d when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.<\/p>\n<p>&nbsp;<\/p>\n<h3>ensureCapacity( )<\/h3>\n<p>If you want to preallocate room for a certain number of characters after a <strong>StringBuffer <\/strong>has been constructed, you can use <strong>ensureCapacity( ) <\/strong>to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a <strong>StringBuffer<\/strong>. <strong>ensureCapacity( ) <\/strong>has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>void ensureCapacity(int <em>capacity<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>capacity <\/em>specifies the size of the buffer.<\/p>\n<p>&nbsp;<\/p>\n<h3>setLength( )<\/h3>\n<p>To set the length of the buffer within a <strong>StringBuffer <\/strong>object, use <strong>setLength( )<\/strong>. Its general form is shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>void setLength(int <em>len<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>len <\/em>specifies the length of the buffer. This value must be nonnegative. When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call <strong>setLength( ) <\/strong>with a value less than the current value returned by <strong>length( )<\/strong>, then the characters stored beyond the new length will be lost. The <strong>setCharAtDemo <\/strong>sample program in the following section uses <strong>setLength( ) <\/strong>to shorten a <strong>StringBuffer<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<h3>charAt( ) and setCharAt( )<\/h3>\n<p>The value of a single character can be obtained from a <strong>StringBuffer <\/strong>via the <strong>charAt( ) <\/strong>method. You can set the value of a character within a <strong>StringBuffer <\/strong>using <strong>setCharAt( )<\/strong>.\u00a0 Their general forms are shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>char charAt(int <em>where<\/em>)<\/p>\n<p>void setCharAt(int <em>where<\/em>, char <em>ch<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>For <strong>charAt( )<\/strong>, <em>where <\/em>specifies the index of the character being obtained. For <strong>setCharAt( )<\/strong>, <em>where <\/em>specifies the index of the character being set, and <em>ch <\/em>specifies the new value of that character. For both methods, <em>where <\/em>must be nonnegative and must not specify a location beyond the end of the buffer. The following example demonstrates <strong>charAt( ) <\/strong>and <strong>setCharAt( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate charAt() and setCharAt().<\/p>\n<p>class setCharAtDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>StringBuffer sb = new StringBuffer(&#8220;Hello&#8221;);<\/p>\n<p>System.out.println(&#8220;buffer before = &#8221; + sb);<\/p>\n<p>System.out.println(&#8220;charAt(1) before = &#8221; + sb.charAt(1));<\/p>\n<p>sb.setCharAt(1, &#8216;i&#8217;);<\/p>\n<p>sb.setLength(2);<\/p>\n<p>System.out.println(&#8220;buffer after = &#8221; + sb);<\/p>\n<p>System.out.println(&#8220;charAt(1) after = &#8221; + sb.charAt(1));<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Here is the output generated by this program:<\/p>\n<p>&nbsp;<\/p>\n<p>buffer before = Hello<\/p>\n<p>charAt(1) before = e<\/p>\n<p>buffer after = Hi<\/p>\n<p>charAt(1) after = i<\/p>\n<p>&nbsp;<\/p>\n<h3>getChars( )<\/h3>\n<p>&nbsp;<\/p>\n<p>To copy a substring of a <strong>StringBuffer <\/strong>into an array, use the <strong>getChars( ) <\/strong>method. It has this general form:<\/p>\n<p>&nbsp;<\/p>\n<p>void getChars(int <em>sourceStart<\/em>, int <em>sourceEnd<\/em>, char <em>target<\/em>[ ], int <em>targetStart<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>sourceStart <\/em>specifies the index of the beginning of the substring, and <em>sourceEnd <\/em>specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from <em>sourceStart <\/em>through <em>sourceEnd<\/em>\u20131. The array that will receive the characters is specified by <em>target. <\/em>The index within <em>target <\/em>at which the substring will be copied is passed in <em>targetStart. <\/em>Care must be taken to assure that the <em>target <\/em>array is large enough to hold the number of characters in the specified substring.<\/p>\n<p>&nbsp;<\/p>\n<h3>append( )<\/h3>\n<p>The <strong>append( ) <\/strong>method concatenates the string representation of any other type of data to the end of the invoking <strong>StringBuffer <\/strong>object. It has overloaded versions for all the built-in types and for <strong>Object<\/strong>. Here are a few of its forms:<\/p>\n<p>&nbsp;<\/p>\n<p>StringBuffer append(String <em>str<\/em>)<\/p>\n<p>StringBuffer append(int <em>num<\/em>)<\/p>\n<p>StringBuffer append(Object <em>obj<\/em>)<\/p>\n<p><strong>\u00a0<\/strong><\/p>\n<p><strong>String.valueOf( ) <\/strong>is called for each parameter to obtain its string representation. The result is appended to the current <strong>StringBuffer <\/strong>object. The buffer itself is returned by each version of <strong>append( )<\/strong>. This allows subsequent calls to be chained together, as shown in the following example:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate append().<\/p>\n<p>class appendDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>String s;<\/p>\n<p>int a = 42;<\/p>\n<p>StringBuffer sb = new StringBuffer(40);<\/p>\n<p>s = sb.append(&#8220;a = &#8220;).append(a).append(&#8220;!&#8221;).toString();<\/p>\n<p>System.out.println(s);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output of this example is shown here:<\/p>\n<p>a = 42!<\/p>\n<p>&nbsp;<\/p>\n<p>The <strong>append( ) <\/strong>method is most often called when the <strong>+ <\/strong>operator is used on <strong>String <\/strong>objects. Java automatically changes modifications to a <strong>String <\/strong>instance into similar operations on a <strong>StringBuffer <\/strong>instance. Thus, a concatenation invokes <strong>append( ) <\/strong>on a <strong>StringBuffer <\/strong>object. After the concatenation has been performed, the compiler inserts a call to <strong>toString( ) <\/strong>to turn the modifiable <strong>StringBuffer <\/strong>back into a constant <strong>String<\/strong>. All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like <strong>StringBuffer<\/strong>? The answer is performance. There are many optimizations that the Java run time can make knowing that <strong>String <\/strong>objects are immutable. Thankfully, Java hides most of the complexity of conversion between <strong>String<\/strong>s and <strong>StringBuffer<\/strong>s. Actually, many programmers will never feel the need to use <strong>StringBuffer <\/strong>directly and will be able to express most operations in terms of the <strong>+ <\/strong>operator on <strong>String <\/strong>variables.<\/p>\n<p>&nbsp;<\/p>\n<h3>insert( )<\/h3>\n<p>The <strong>insert( ) <\/strong>method inserts one string into another. It is overloaded to accept values of all the simple types, plus <strong>String<\/strong>s and <strong>Object<\/strong>s. Like <strong>append( )<\/strong>, it calls <strong>String.valueOf( ) <\/strong>to obtain the string representation of the value it is called with. This string is then inserted into the invoking <strong>StringBuffer <\/strong>object. These are a few of its forms:<\/p>\n<p>&nbsp;<\/p>\n<p>StringBuffer insert(int <em>index<\/em>, String <em>str<\/em>)<\/p>\n<p>StringBuffer insert(int <em>index<\/em>, char <em>ch<\/em>)<\/p>\n<p>StringBuffer insert(int <em>index<\/em>, Object <em>obj<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>index <\/em>specifies the index at which point the string will be inserted into the invoking <strong>StringBuffer <\/strong>object. The following sample program inserts \u201clike\u201d between \u201cI\u201d and \u201cJava\u201d:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate insert().<\/p>\n<p>class insertDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>StringBuffer sb = new StringBuffer(&#8220;I Java!&#8221;);<\/p>\n<p>sb.insert(2, &#8220;like &#8220;);<\/p>\n<p>System.out.println(sb);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output of this example is shown here:<\/p>\n<p>I like Java!<\/p>\n<p>&nbsp;<\/p>\n<h3>reverse( )<\/h3>\n<p>You can reverse the characters within a <strong>StringBuffer <\/strong>object using <strong>reverse( )<\/strong>, shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>StringBuffer reverse( )<\/p>\n<p>&nbsp;<\/p>\n<p>This method returns the reversed object on which it was called. The following program demonstrates <strong>reverse( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Using reverse() to reverse a StringBuffer.<\/p>\n<p>class ReverseDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>StringBuffer s = new StringBuffer(&#8220;abcdef&#8221;);<\/p>\n<p>System.out.println(s);<\/p>\n<p>s.reverse();<\/p>\n<p>System.out.println(s);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Here is the output produced by the program:<\/p>\n<p>abcdef<\/p>\n<p>fedcba<\/p>\n<p>&nbsp;<\/p>\n<h3>delete( ) and deleteCharAt( )<\/h3>\n<p>Java 2 added to <strong>StringBuffer <\/strong>the ability to delete characters using the methods <strong>delete( ) <\/strong>and <strong>deleteCharAt( )<\/strong>. These methods are shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>StringBuffer delete(int <em>startIndex<\/em>, int <em>endIndex<\/em>)<\/p>\n<p>StringBuffer deleteCharAt(int <em>loc<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>The <strong>delete( ) <\/strong>method deletes a sequence of characters from the invoking object. Here, <em>startIndex <\/em>specifies the index of the first character to remove, and <em>endIndex <\/em>specifies an index one past the last character to remove. Thus, the substring deleted runs from <em>startIndex <\/em>to <em>endIndex<\/em>\u20131. The resulting <strong>StringBuffer <\/strong>object is returned. The <strong>deleteCharAt( ) <\/strong>method deletes the character at the index specified by <em>loc<\/em>. It returns the resulting <strong>StringBuffer <\/strong>object. Here is a program that demonstrates the <strong>delete( ) <\/strong>and <strong>deleteCharAt( ) <\/strong>methods:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate delete() and deleteCharAt()<\/p>\n<p>class deleteDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>StringBuffer sb = new StringBuffer(&#8220;This is a test.&#8221;);<\/p>\n<p>sb.delete(4, 7);<\/p>\n<p>System.out.println(&#8220;After delete: &#8221; + sb);<\/p>\n<p>sb.deleteCharAt(0);<\/p>\n<p>System.out.println(&#8220;After deleteCharAt: &#8221; + sb);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The following output is produced:<\/p>\n<p>After delete: This a test.<\/p>\n<p>After deleteCharAt: his a test.<\/p>\n<p>&nbsp;<\/p>\n<h3>replace( )<\/h3>\n<p>Another method added to <strong>StringBuffer <\/strong>by Java 2 is <strong>replace( )<\/strong>. It replaces one set of characters with another set inside a <strong>StringBuffer <\/strong>object. Its signature is shown here: StringBuffer replace(int <em>startIndex<\/em>, int <em>endIndex<\/em>, String <em>str<\/em>) The substring being replaced is specified by the indexes <em>startIndex <\/em>and <em>endIndex<\/em>. Thus, the substring at <em>startIndex <\/em>through <em>endIndex<\/em>\u20131 is replaced. The replacement string is passed in <em>str<\/em>. The resulting <strong>StringBuffer <\/strong>object is returned. The following program demonstrates <strong>replace( )<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">\/\/ Demonstrate replace()<\/p>\n<p>class replaceDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>StringBuffer sb = new StringBuffer(&#8220;This is a test.&#8221;);<\/p>\n<p>sb.replace(5, 7, &#8220;was&#8221;);<\/p>\n<p>System.out.println(&#8220;After replace: &#8221; + sb);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Here is the output:<\/p>\n<p>After replace: This was a test.<\/p>\n<p>&nbsp;<\/p>\n<h3>substring( )<\/h3>\n<p>Java 2 also added the <strong>substring( ) <\/strong>method, which returns a portion of a <strong>StringBuffer<\/strong>. It has the following two forms:<\/p>\n<p>&nbsp;<\/p>\n<p>String substring(int <em>startIndex<\/em>)<\/p>\n<p>String substring(int <em>startIndex<\/em>, int <em>endIndex<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>The first form returns the substring that starts at <em>startIndex <\/em>and runs to the end of the invoking <strong>StringBuffer <\/strong>object. The second form returns the substring that starts at <em>startIndex <\/em>and runs through <em>endIndex<\/em>\u20131. These methods work just like those defined for <strong>String <\/strong>that were described earlier.<\/p>\n<p>&nbsp;<\/p>\n<h2>StringBuffer Methods Added by Java 2, Version 1.4<\/h2>\n<p>&nbsp;<\/p>\n<p>Java 2, version 1.4 added several new methods to <strong>StringBuffer<\/strong>. They are summarized in the following table.<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"271\">Method<\/td>\n<td width=\"384\">Description<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">CharSequence subSequence(int <em>startIndex<\/em>,<\/p>\n<p>int <em>stopIndex<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Returns a substring of the invoking string, beginning at <em>startIndex <\/em>and stopping at <em>stopIndex<\/em>. This method is<\/p>\n<p>required by the <strong>CharSequence <\/strong>interface, which is now implemented by <strong>StringBuffer<\/strong>.<\/p>\n<p>&nbsp;<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">int indexOf(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Searches the invoking <strong>StringBuffer <\/strong>for the first occurrence of <em>str<\/em>. Returns the index of the match, or \u20131 if no match is found.<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">int indexOf(String <em>str<\/em>, int <em>startIndex<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Searches the invoking <strong>StringBuffer <\/strong>for the first occurrence of <em>str<\/em>, beginning at <em>startIndex<\/em>. Returns the index of the match, or \u20131 if no match is found.<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">int lastIndexOf(String <em>str<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Searches the invoking <strong>StringBuffer <\/strong>for the last occurrence of str. Returns the index of the match, or \u20131 if no match is found.<\/td>\n<\/tr>\n<tr>\n<td width=\"271\">int lastIndexOf(String <em>str<\/em>, int <em>startIndex<\/em>)<\/p>\n<p>&nbsp;<\/td>\n<td width=\"384\">Searches the invoking <strong>StringBuffer <\/strong>for the last occurrence of <em>str<\/em>, beginning at <em>startIndex<\/em>. Returns the index of the match, or \u20131 if no match is found.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Aside from <strong>subSequence( )<\/strong>, which implements a method required by the <strong>CharSequence <\/strong>interface, the other methods allow a <strong>StringBuffer <\/strong>to be searched for an occurrence of a <strong>String<\/strong>. The following program demonstrates <strong>indexOf( ) <\/strong>and <strong>lastIndexOf( )<\/strong>.<\/p>\n<p>&nbsp;<\/p>\n<table>\n<tbody>\n<tr>\n<td width=\"655\">class IndexOfDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>StringBuffer sb = new StringBuffer(&#8220;one two one&#8221;);<\/p>\n<p>int i;<\/p>\n<p>i = sb.indexOf(&#8220;one&#8221;);<\/p>\n<p>System.out.println(&#8220;First index: &#8221; + i);<\/p>\n<p>i = sb.lastIndexOf(&#8220;one&#8221;);<\/p>\n<p>System.out.println(&#8220;Last index: &#8221; + i);<\/p>\n<p>}<\/p>\n<p>}<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>The output is shown here.<\/p>\n<p>First index: 0<\/p>\n<p>Last index: 8<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>String Handling &nbsp; In Java a string is a sequence of characters. Java implements strings as objects of type String. For example, Java has methods to compare two strings, search&hellip; <\/p>\n","protected":false},"author":1,"featured_media":3477,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[83],"tags":[],"aioseo_notices":[],"amp_enabled":true,"_links":{"self":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3463"}],"collection":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/comments?post=3463"}],"version-history":[{"count":2,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3463\/revisions"}],"predecessor-version":[{"id":3489,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3463\/revisions\/3489"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media\/3477"}],"wp:attachment":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media?parent=3463"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/categories?post=3463"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/tags?post=3463"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}