Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Department of Collegiate and Technical Education

ADVANCED JAVA PROGRAMMING– 21CS642

Computer Science and Engineering

String Handling
(Module 3 )

Computer Science & Engineering – 21CS642


String Handling:
The String Constructors, String Length, Special String Operations,
Character Extraction, String Comparison, Searching Strings,
Modifying a String, Data Conversion Using valueOf(), Changing the
case of characters within a String, String Buffer, String Builder
String Handling

• A string is a sequence of characters (or numbers or symbols or all


together) enclosed within double quotes (" ").
• Example: "Java Programming".
• Generally, string is a sequence of characters but in java, string
is an object that represents a sequence of characters.
• The java.lang.String class is used to create string object.
• Java implements strings as objects of type String.
• The basic aim of String Handling concept is storing the string data
in the memory, manipulating the data of the String, retrieving the
part of the String etc.
• String Handling provides a lot of concepts that can be performed
on a string such as concatenation of string, comparison of string,
find sub string etc.
String Handling
• To store the string data and to perform various operation on String
data, we have three predefined classes they are:
1) String
2) StringBuffer
3) StringBuilder
• Above 3 classes are defind in java.lang
• All are declared final (which means that none of these classes may
be subclassed.)
• There are two ways to create String object:
1) By string literal
2) By new keyword
The StringConstructors
1) To create an empty string, use String s = new String();
2) To create a String initialized by an array of characters, use
String(char chars[])
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
3) We can specify the sub range of character array as an initializer
using
String(char chars[], int startindex, int num);
Here, startindex is from which index sub string begins, and
num is number of characters to use
char chars[]={‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};
String s=new String(chars, 2, 3);
Now, s contains cde
4) We can construct a string object that contains the same character
sequence as another object using String(String strobj[])
class MakeString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a’};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
} Output:
Java
Java
5) String class provides constructors that initialize a string when given
a byte array.
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int num)
• Here, asciiChars specifies the array of bytes.
• In both the constructors, the byte-to-character conversion is done
by using the default character encoding of the platform.
class SubStringCons
{
public static void main(String args[])
{
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2); OUTPUT:
} ABCDEF
} CDE
String Constructors Added by J2SE 5:
• 2 Constructors.

String(int codePoints[ ], int startIndex, int num)


• Supports the extended Unicode character set
• Here, codePoints is an array that contains Unicode code points. The
resulting string is constructed from the range that begins at
startIndex mentioned and runs for number of characters.

String(StringBuilder sbo)
• Supports the new StringBuilder class.
• This constructs a String from the StringBuilder passed in sbo.
The String Length
• The length of a string is the number of characters that it contains.
• Use int length( )
class stringlength
{
public static void main(String args[])
{
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
}
}
Special String Operations
1) The automatic creation of new string instances from string literals.
2) Concatenation of multiple String objects by use of the + operator.
3) The conversion of other data types to a string representation.
class ppp
{
public static void main(String args[])
{
char chars[] = {'a','b','c’};
String s1 = new String (chars);
String s2 = "abc"; OUTPUT:
System .out.println(s1); abc
System .out.println(s2); abc
3
System .out.println("abc".length());
}
}
The String Concatenation
• The + operator, which concatenates 2 strings, producing a
String object as the result.
class p
{
public static void main(String args[])
{
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
}
}
OUTPUT
He is 9 years old
String Concatenation with Other Data Types:
• We can concatenate strings with other types of data. For example,
consider this slightly different version of the earlier example:
class concat
{
public static void main(String args[])
{
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
}
} OUTPUT: He is 9 years old
Note: Here, age is an int rather than another String, but the output
produced is the same as before. This is because the int value in age
is automatically converted into its string representation within a
String object.
Note: Be careful when you mix other types of operations with
string concatenation expressions,
class Example1
{
public static void main(String args[])
{
String s = "four: " + 2 + 2;
System.out.println(s); OUTPUT:
}
} four: 22

class Example2
{
public static void main(String args[])
{
OUTPUT:
String s = "four: " + (2 + 2);
four: 4
System.out.println(s);
}
}
String Conversion and toString( ):
class Box
{ double width, height, depth;
Box(double w, double h, double d)
{ width = w;
height = h;
depth = d;
}
public String toString()
{ return "Dimensions are " + width + " by " + depth + " by " + height + ".";
}
}
class example3
{ public static void main(String args[])
{ Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}
CharacterExtraction
• The String class provides a number of ways in which characters can
be extracted from a String object.
• charAt( ): To extract a single character from a String, we can refer
directly to an individual character via the charAt( ) method.
char charAt(int where) //from which index to extract
• The value of where must be nonnegative and specify a location
within the string.
• charAt( ) returns the character at the specified location.
class p
{
public static void main(String args[])
{
char ch;
ch = "abc".charAt(1);
System.out.println(ch);
}
}
The getChars( )
• The getChars( ) method is used to extract more than one character at
a time.
void getChars(int where, int to, char target[], int targetstart)
• Here, where specifies the index of the beginning of the substring,
and to specifies an index that is one past the end of the desired
substring.
• The array that will receive the characters is specified by target.
• The index within target at which the substring will be copied is
passed in targetstart.
• Always the target array is large enough to hold the number of
characters in the specified substring.
class getCharsDemo
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10, end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}

OUTPUT:
demo
getBytes( )
• There is an alternative to getChars( ) that stores the characters in an
array of bytes.
• The getBytes( ) uses the default character-to-byte conversions
provided by the platform.
byte[ ] getBytes( )
• It is the most useful when we are exporting a String value into an
environment that does not support 16-bit Unicode characters.
• For example, most Internet protocols and text file formats use 8-bit
ASCII for all text interchange.

toCharArray( )
• The toCharArray( ) is used to convert all the characters in a String
object into a character array.
• It returns an array of characters for the entire string.
char[ ] toCharArray( )
String Comparison
• The String class includes several methods that compare strings or
substrings within strings.
equals( ) and
equalsIgnoreCase( )
• To compare two strings for equality, use equals( ).
Syntax: boolean equals(Object str)
• Here, str is the String object being compared with the invoking
String object.
• Returns: True, if the string contain the same characters in the same
order, otherwise False.
equalsIgnoreCase( ):
• To perform a comparison that ignores case differences, call
equalsIgnoreCase( ).
Syntax: boolean equalsIgnoreCase(String str)
class stringcompare
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +s1.equals(s4));
System.out.println(s1+ " equalsIgnoreCase " + s4 + " -> "
+s1.equalsIgnoreCase(s4));
}
} Output:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
The regionMatches( ):
• This method compares a specific region inside a string with another
specific region in another string.
• It has two methods:
public class regionmatching
{
public static void main(String args[])
{
String str1 = "Collection of tutorials";
String str2 = "Consists of different tutorials";
/* Matches characters from index 14 in str1 to characters from index 22 in str2
considering same case of the letters.*/
boolean match1 = str1.regionMatches(14, str2, 22, 9);
System.out.println("region matched = " + match1);
str2 = "Consists of different Tutorials";
match1 = str1.regionMatches(14, str2, 22, 9);
System.out.println("region matched = " + match1);
//considering different case, "true" is set which will ignore case when matched
str2 = "Consists of different Tutorials";
match1 = str1.regionMatches(true, 14, str2, 22, 9);
System.out.println("region matched = " + match1);
}
}
The startsWith( ) and endsWith( ) methods
• These are the specialized forms of regionMatches( ).
• startsWith( ), determines whether a given String begins with a
specified string.
• endsWith( ) determines whether the String in question ends with a
specified string.
boolean startsWith(String str)
boolean endsWith(String str)
• Here, str is the String being tested. If matches, true is returned.
Otherwise, false is returned.
"Foobar".endsWith("bar") and
"Foobar".startsWith("Foo") are both true.
• A second form of startsWith( ), shown here, lets you specify a
starting point:
boolean startsWith(String str, int startIndex)
• Here, startIndex specifies the index into the invoking string at which
point the search will begin.
"Foobar".startsWith("bar", 3) returns true.
The equals( ) Versus ==
• The equals( ) method and the == operator perform two different operations.
• The equals( ) method compares the characters inside a String object.
• The == operator compares two object references refer to the same instance.
public class equals==
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2));
System.out.println((s1 == s2));
Output:
}
True
}
false
• The values of s1 and s2 are same. So s1.equals(s2) is true.
• The objects s1 and s2 are not referencing to same instance. So s1==s2 is false.
The compareTo( ) method
• This method is used to check which string is less than, equal to, or
greater than the next.
• It provides the following result which depends on the condition.

int compareTo(String str)


• Here, str is the String being compared with the invoking String.
// A bubble sort for Strings using compareTo( )
class comparetomethod
{
static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country“ };
public static void main(String args[]) output:
Now
{ for(int j = 0; j < arr.length; j++)
aid
{ for(int i = j + 1; i < arr.length; i++) all
{ if(arr[i].compareTo(arr[j]) < 0) come
country
{ String t = arr[j];
for
arr[j] = arr[i]; good
arr[i] = t; is
men
}
of
} the
System.out.println(arr[j]); the
their
}
time
} to
} to
• Note: compareTo( ) takes into account uppercase and lowercase
letters. The word “Now” 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 compareToIgnoreCase( )
int compareToIgnoreCase(String str)
// A bubble sort for Strings. Using compareTo( )
class comparetomethod
{
static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country“ };
Output:
public static void main(String args[]) aid
{ for(int j = 0; j < arr.length; j++) all
{ for(int i = j + 1; i < arr.length; i++) come
country
{ if(arr[i].compareToIgnoreCase(arr[j]) < 0) for
{ String t = arr[j]; good
arr[j] = arr[i]; is
men
arr[i] = t; Now
} of
} the
the
System.out.println(arr[j]); their
} time
} to
to
}
Searching Strings
• The String class provides two methods that allow us to search a
string for a specified character or substring: These methods can also
be overloaded in many ways.
1) indexOf( ) Searches for the first occurrence of a character or
substring.
int indexOf(int ch) //search for first occurrence of character
int indexOf(String str) // search first occurrence of substring
1) lastIndexOf( ) Searches for the last occurrence of a character or
substring.
int lastIndexOf(int ch) //search for first occurrence of character
int lastIndexOf(String str) // search last occurrence of substring
• In both the above cases, ch and str are the character and string
being searched/wanted.
• In all cases, the methods return the index at which the character or
substring was found, or –1 on failure.
• We can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
• Here, startIndex specifies the index at which point the search
begins and to
• For indexOf( ), the search runs from startIndex to the end of the
string.
• For lastIndexOf( ), the search runs from startIndex to zero.
class searchindex
{
public static void main(String args[])
{
String s="Now is the time for all good men to come to the aid of their country";
System.out.println(s);
System.out.println(“The indexOf(t) = " + s.indexOf('t'));
System.out.println(“The lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println(“The indexOf(the) = " + s.indexOf("the"));
System.out.println(“The lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println(“The indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println(“The lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println(“The indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println(“The lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}
OUTPUT:
Now is the time for all good men to come to the aid of their country.
The indexOf(t) = 7
The lastIndexOf(t) = 65
The indexOf(the) = 7
The lastIndexOf(the) = 55
The indexOf(t, 10) = 11
The lastIndexOf(t, 60) = 55
The indexOf(the, 10) = 44
The lastIndexOf(the, 60) = 55
Modifying a String
• To modify a String, we must either copy it into a StringBuffer or
StringBuilder, or use one of the following String methods.
substring( )
• It is used to extract a substring. It has two forms.
String substring(int startIndex) //startIndex specifies the
index at which substring will begin & till the end of invoking string.
String substring(int startIndex, int endIndex)
• Specifies both the beginning and ending index of the substring
class p
{
public static void main(String args[])
{
String org = "This is a test. This is, too.";
String sub = org.substring(5);
String sub1 = org.substring(5,7);
System.out.println(sub); OUTPUT:
System.out.println(sub1); is a test. This is, too.
} is
}
class stringreplacement
{ public static void main(String args[])
{ String org = "This is a test. This is, too.";
String search = "is";
String sub = "was"; OUTPUT:
String result = ""; This is a test. This is, too.
Thwas is a test. This is, too.
int i;
Thwas was a test. This is, too.
do Thwas was a test. Thwas is, too.
{ System.out.println(org); Thwas was a test. Thwas was, too.
i = org.indexOf(search);
if(i != -1)
{ result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}
The concat()
• Concatenates two string exactly similar to +.
String concat(String str)
str will be concatenated with the invoking string
class stringconcat
{
public static void main(String args[])
{
String s1 = "one";
String s2 = s1.concat("two");
System.out.println(s2);
String s1 = "one";
String s2 = s1 + "two";
System.out.println(s2);
} OUTPUT:
} onetwo
onetwo
The replace():
• It has two forms.
• First form: Original character is replaced with the new replacement
character.
String replace(char original, char replacement)
• Second form: Replaces one character sequence with another.
String replace(CharSequence original, CharSequence
replacement)

class replacechar
{
public static void main(String args[])
{
String s = "Hello".replace('l', 'w’);
System.out.println(s);
String s1 = "Hellommmmmmm".replace("mm", "nn");
System.out.println(s1);
OUTPUT:
}
Hewwo
}
Hellonnnnnnn
The trim( ):
• It returns a copy of the invoking string from which any leading and
trailing whitespace has been removed.
String trim( )

class trimstring
{
public static void main(String args[])
{
String s = " Hello World ";
System.out.println(s.length());
System.out.println(s);
String s1 = s.trim(); OUTPUT:
System.out.println(s1); 19
System.out.println(s1.length()); Hello World
} Hello World
} 11
Data Conversion using valueOf()
• The valueOf() method converts all the different types of values into
human readable string format.
• It has various overloaded forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
public class dataconversion
{
public static void main(String args[])
{
int value=30;
String s1;
//s1=value; // error : incompatible types
s1=String.valueOf(value);
System.out.println(“Result 1: ”+ s1+10);//concatenating string with 10
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };
//s1=arr; // error : incompatible types
s1=String.valueOf(arr);
System.out.println(“Result 2: ”+ s1);
}
}

OUTPUT:
Result 1: 40
Result 2: abcdefg
Changing the case of the characters within a String
• toLowerCase( ) converts all the characters in a string from
uppercase to lowercase.
• toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase.
• Nonalphabetical characters, such as digits, are unaffected.
String toLowerCase( )
String toUpperCase( )
• Both methods return a String object that contains the uppercase or
lowercase equivalent of the invoking String.
class ChangeCase
{
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
Changing the case of the characters within a String
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}

OUTPUT:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
ADDITIONAL STRING METHODS :
StringBuffer
It is a peer a class of String class.
Why StringBuffer?
1) The String class is used to manipulate character strings that cannot
be changed, objects of type String are read only and immutable.
2) The StringBuffer class is used to represent characters that can be
modified.
3) String represents fixed-length, immutable character sequences.
4) StringBuffer represents growable and writeable character
sequences.
5) StringBuffer may have characters and substrings inserted in the
middle or appended to the end.
6) Even String class is used more, StringBuffer is more
advantageous.
• StringBuffer defines four constructors:
• StringBuffer( ): The default constructor reserves room for 16
characters without reallocation
• StringBuffer(int size): It accepts an integer argument that explicitly
sets the size of the buffer.
• StringBuffer(String str): Accepts a String argument
• StringBuffer(CharSequence chars): Creates an object that contains
the character sequence contained in chars.
length( ) and capacity( )
• The length() is used to find the length of a StringBuffer.
• The capacity() is used to find the total allocated capacity. Additional
room will be automatically created for the string buffer object.
int length( )
int capacity( )

class lenghthandcapacity
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer(“Hello”);
System.out.println(“Buffer = " + sb);
System.out.println(“Length = " + sb.length());
OUTPUT:
System.out.println(“Capacity = " + sb.capacity());
Buffer = Hello
}
} Length = 5
Capacity = 21
ensureCapacity( )
• This method is used to preallocate room for a certain number of
characters after a StringBuffer has been constructed.
• The ensureCapacity( ) sets the size of the buffer.
• It is useful if we know in advance that we will be appending a large
number of small strings to a StringBuffer.
void ensureCapacity(int capacity)
• Here, capacity specifies the size of the buffer.

setLength( )
• The setLength( ) is used to set the length of the buffer within a
StringBuffer object.
void setLength(int len)
• Here, len specifies the length of the buffer. This value must be
nonnegative.
charAt( ) and setCharAt( )
• The charAt( ) is used to obtain the value of a single character from a
StringBuffer.
char charAt(int where)
• Here, where specifies the index of the character being obtained.
• The setCharAt( ) is used to set the value of a character within a
StringBuffer.
void setCharAt(int where, char ch)
• Here, where specifies the index of the character being set, and ch
specifies the new value of that character.
class setCharAtDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println(“Buffer before = " + sb);
System.out.println(“The charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i’);
sb.setLength(2);
System.out.println(“Buffer after = " + sb);
System.out.println(“The charAt(1) after = " + sb.charAt(1));
} OUTPUT:
} buffer before = Hello
charAt(1) before = e
Buffer after = Hi
The charAt(1) after = i
getChars( )
• The getChars( ) is used to copy a substring of a StringBuffer into an
array.
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
• Here, sourceStart - index of the beginning of the substring.
sourceEnd - index that is one past the end (end-1) of the desired
substring. target[] – receives the string. targetStart-starting index of
target.
class getchars
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("This is a GECK of the getChars method");
int start = 10, end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}

OUTPUT:
GECK
append( )
• It concatenates the string representation of any other type of data to
the end of the invoking StringBuffer object.
• It has several overloaded versions.
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
• String.valueOf( ) is called automatically for each parameter to obtain
its string representation.
class appendDemo
{ OUTPUT:
public static void main(String args[]) The value of a = 42!
{
int a = 42;
StringBuffer sb = new StringBuffer(“The value of ”);
String s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
insert( )
• It inserts one string into another.
• It is overloaded to accept values of all the simple types, plus
Strings, Objects, and CharSequences.
• Like append( ), it calls String.valueOf( ) automatically to obtain
the string representation of the value it is called with.
• This string is then inserted into the invoking StringBuffer object.
• These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
• Here, index specifies the index at which point the string will be
inserted into the invoking StringBuffer object.
class insertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}

OUTPUT:
I like Java!
reverse( )
• It is used to reverse the characters within a StringBuffer object:
StringBuffer reverse( )

class ReverseDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("abcdef");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
OUTPUT:
abcdef
fedcba
delete( ) and deleteCharAt( ):
• The delete( ) deletes a sequence of characters from invoking object.
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
• Here, startIndex - index of the first character to remove. endIndex -
indexone past (end-1) the last character to remove.
• The deleteCharAt( ) deletes the character at index specified by loc.
class Delete
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(5);
System.out.println("After deleteCharAt: " + sb); OUTPUT:
} After delete: This a test
} After deleteCharAt: This test
replace( ):
• It is used to replace one set of characters with another set inside a
StringBuffer object.
StringBuffer replace(int startIndex, int endIndex, String str)
• Here, startIndex and endIndex represents the substring being
replaced between. (end-1). The str - replacement string.
class p
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was"); //7 means upto 6 only
System.out.println("After replace: " + sb);
}
} OUTPUT:
After replace: This was a test.
substring( ):
• It is used to obtain a portion of a StringBuffer. It has 2 forms.
String substring(int startIndex)
String substring(int startIndex, int endIndex)
• First: Returns the substring that starts at startIndex and runs to the
end of the invoking StringBuffer object.
• Second: Returns the substring that starts at startIndex and runs
through endIndex–1.
• Note: These methods same as those defined for String class.
class Substring
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer(“KKGEC KRPET");
String sb1=sb.substring(2, 9);
System.out.println(sb1);
OUTPUT:
}
GEC KRP
}
• The lastIndexOf()
class IndexOfDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("one two one");
int i = sb.indexOf("one");
System.out.println("First index: " + i);
i = sb.lastIndexOf("one");
System.out.println("Last index: " + i);
}
}
OUTPUT:
First index: 0
Last index: 8
StringBuilder
• J2SE 5 adds a new string class to Java’s already powerful string
handling capabilities, which is called StringBuilder.
• It is identical to StringBuffer except for one important
difference: it is not synchronized, which means that it is not
thread-safe.
• The advantage of StringBuilder is faster performance.
• However, in cases in which we are using multithreading, we
must use StringBuffer rather than StringBuilder.

You might also like