Module 2-String Handling(BIS402)
Module 2-String Handling(BIS402)
HANDLING
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
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
• Additional String Methods
• StringBuffer
• StringBuilder.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
•
STRING
String is a sequence of characters.
HANDLING
• Java implements strings as objects of type String – which allows Java to provide a full
complement of features that make string handling convenient.
• When you create a String object, you are creating a string that cannot be changed. That is,
once a String object has been created, you cannot change the characters that comprise that
string.
• But 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 String
object is created that contains the modifications.
• The original string is left unchanged. This approach is used because fixed, immutable strings
can be implemented more efficiently than changeable ones.
• For those cases in which a modifiable string is desired, Java provides two options:
StringBuffer and StringBuilder. Both hold strings that can be modified after they are
created.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
(iii) You can specify a subrange of a character array as an initializer using the
following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars
specifies the number of characters to use.
• Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
• This initializes s with the characters “cde”.
3/6/2025
(iv) You can construct a String object (v) The String class provides
that contains the same character constructors that initialize a string when
sequence as another String object: given a byte array.
String(String strObj)
• Here, strObj is a String object. • Here, asciiChars specifies the array of
bytes. The second form allows you to
specify a subrange.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
STRING LENGTH
• The length of a string is the number of characters that it contains.
• To obtain this value, call the length( ) method, shown here:
int length( )
• The following fragment prints “3”, since there are three characters in the string s:
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
(ii) String Concatenation
• In general, Java does not allow
operators to be applied to String
objects.
• The one exception to this rule is
the + operator, which concatenates
two strings, producing a String
object as the result.
• This allows you to chain together a
series of + operations.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
3/6/2025
(i) charAt( )
CHARACTER • To extract a single character from a String,
EXTRACTION you can refer directly to an individual
character via the charAt( ) method.
• The String class provides a number • It has this general form:
of ways in which characters can be
extracted from a String object. char charAt(int where)
• Although the characters that • Here, where is the index of the character that
comprise a string within a String you want to obtain. The value of where must
object cannot be indexed as if they be nonnegative and specify a location within
were a character array, many of the the string.
String methods employ an index • charAt( ) returns the character at the
into the string for their operation. specified location. For example,
• Like arrays, the string indexes
begin at zero.
3/6/2025
(ii) getChars( )
• To extract more than one character at a time,
getChars( ) method is used .
• It has this general form:
• void getChars(int sourceStart, int sourceEnd,
char target[ ], int targetStart)
• Here, sourceStart specifies the index of the beginning
of the substring, and sourceEnd specifies an index that
is one past the end of the desired substring. Thus,
the substring contains the characters from sourceStart
through sourceEnd–1.
• 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.
• Care must be taken to assure that the target array is
large enough to hold the number of characters in the
specified substring.
3/6/2025
• (iii) getBytes( ) (iv) toCharArray( )
• An alternative to getChars( ), that stores • toCharArray( ) is used to convert all the
the characters in an array of bytes. characters in a String object into a
character array.
• This method uses the default character-
to-byte conversions provided by the • It returns an array of characters for the
platform. entire string.
• Here is its simplest form: • It has this general form:
byte[ ] getBytes( ) char[ ] toCharArray( )
• This function is provided as a
convenience, since it is possible to use
getChars( ) to achieve the same result.
3/6/2025
STRING COMPARISON
• The String class includes several methods that • To perform a comparison that ignores case
compare strings or substrings within strings. differences, call equalsIgnoreCase( ).
(i) equals( ) and equalsIgnoreCase( ) • When it compares two strings, it considers A-Z to be
the same as a-z.
• To compare two strings for equality, use equals( ).
• It has this general form:
• It has this general form:
boolean equalsIgnoreCase(String str)
boolean equals(Object str)
• Here, str is the String object being compared with • Here, str is the String object being compared with the
invoking String object.
the invoking String object.
• It returns true if the strings contain the same
• It returns true if the strings contain the same characters in the same order, and false otherwise.
characters in the same order, and false otherwise.
• The comparison is case-sensitive.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
(ii) regionMatches( )
• The regionMatches( ) 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.
• The general forms for these two methods:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)
• For both versions, startIndex specifies the index at which the region begins within the invoking String
object.
• The String being compared is specified by str2.
• The index at which the comparison will start within str2 is specified by str2StartIndex.
• The length of the substring being compared is passed in numChars.
• In the second version, if ignoreCase is true, the case of the characters is ignored. Otherwise, case is
significant.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
(v) compareTo( )
• For sorting applications, you need to know which is less
than, equal to, or greater than the next.
• A string is
(i) less than another if it comes before the other in
dictionary order.
(ii) greater than another if it comes after the other
in dictionary order.
• The String method compareTo( ) serves this purpose.
• It has this general form:
int compareTo(String str)
• Here, str is the String being compared with the
invoking String. The result of the comparison is
returned and is interpreted, as shown here:
3/6/2025
3/6/2025
(vi) Searching Strings
• The String class provides two methods that allow you to • To search for the first or last occurrence of a substring, use
search a string for a specified character or substring:
int indexOf(String str)
indexOf( ) Searches for the first occurrence of a
character or substring. int lastIndexOf(String str)
lastIndexOf() Searches for the last occurrence of a Here, str specifies the substring.
character or substring. • You can specify a starting point for the search using these
• These two methods are overloaded in several different forms:
ways. int indexOf(int ch, int startIndex)
• In all cases, the methods return the index at which the int lastIndexOf(int ch, int startIndex)
character or substring was found, or –1 on failure.
int indexOf(String str, int startIndex)
• To search for the first occurrence of a character, use
int lastIndexOf(String str, int startIndex)
int indexOf(int ch)
• Here, startIndex specifies the index at which point the search
• To search for the last occurrence of a character, use begins.
int lastIndexOf(int ch) • For indexOf( ), the search runs from startIndex to the end
• Here, ch is the character being sought. of the string.
• For lastIndexOf( ), the search runs from startIndex to zero.
3/6/2025
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
MODIFYING A STRING
• Because String objects are immutable, whenever you want to modify a String, you must either copy it into a
StringBuffer or StringBuilder, or use one of the following String methods.
(i) substring( )
• You can extract a substring using substring( ). It has two forms.
• The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin.
This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string.
• The second form of substring( ) allows you to specify both the beginning and ending index of the
substring:
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point.
• The string returned contains all the characters from the beginning index, up to, but not including, the ending
index.
3/6/2025
3/6/2025
(ii) concat( ) (iii) replace( )
• To concatenate two strings use --- concat() • The replace( ) method has two forms.
String concat(String str) • The first replaces all occurrences of one character in the
invoking string with another character.
• This method creates a new object that contains the
invoking string with the contents of str appended to • It has the following general form:
the end.
String replace(char original, char replacement)
• concat( ) performs the same function as +. For
example, Here, original specifies the character to be replaced by
the character specified by replacement.
String s1 = "one";
• The resulting string is returned. For example,
String s2 = s1.concat("two");
String s = "Hello".replace('l', 'w’);
puts the string “onetwo” into s2.
puts the string “Hewwo” into s.
• It generates the same result as the following
sequence: • The second form of replace( ) replaces one character
sequence with another.
String s1 = "one";
• It has this general form:
String s2 = s1 + "two";
String replace(CharSequence original, CharSequence
replacement)
• This form was added by J2SE 5.
3/6/2025
(iv) trim( )
• The trim( ) method returns a copy of the
invoking string from which any leading and
trailing whitespace has been removed.
• It has this general form:
String trim( )
• Here is an example:
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
• The trim( ) method is quite useful when
you process user commands.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
• All of the simple types are converted to their common String representation.
• Any object that you pass to valueOf( ) will return the result of a call to the object’s
toString() method.
• For most arrays, valueOf( ) returns a rather cryptic string, which indicates that it is an array
of some type.
• There is a special version of valueOf( ) that allows you to specify a subset of a char array.
• It has this general form:
static String valueOf(char chars[ ], int startIndex, int numChars)
Here, chars is the array that holds the characters,
startIndex is the index into the array of characters at which the desired substring
begins, and
numChars specifies the length of the substring.
3/6/2025
CHANGING THE CASE OF
CHARACTERS WITHIN A STRING
• The method toLowerCase( ) converts all the
characters in a string from uppercase to
lowercase.
• The toUpperCase( ) method converts all the
characters in a string from lowercase to
uppercase.
• Nonalphabetical characters, such as digits, are
unaffected.
• The general forms of these methods:
String toLowerCase( )
String toUpperCase( )
• Both methods return a String object that
contains the uppercase or lowercase equivalent
of the invoking String. 3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
STRINGBUFFER
• StringBuffer is a peer class of String that provides much of the functionality of
strings.
• String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences.
• StringBuffer may have characters and substrings inserted in the middle or
appended to the end.
• Java uses both classes heavily, but many programmers deal only with String and let
Java manipulate StringBuffers behind the scenes by using the overloaded +
operator.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
StringBuffer Constructors
• StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
• The default constructor 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 String argument that sets the initial contents of the StringBuffer object and
reserves room for 16 more characters without reallocation.
• StringBuffer allocates room for 16 additional characters when no specific buffer length is requested,
because reallocation is a costly process in terms of time.
• By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take
place.
• The fourth constructor creates an object that contains the character sequence contained in chars.
3/6/2025
(i) length( ) and capacity( ) (ii) ensureCapacity( )
• The current length of a StringBuffer can be found via the • If you want to preallocate room for a certain number of characters
length( ) method, while the total allocated capacity can be after a StringBuffer has been constructed, you can use
found through the capacity( ) method. ensureCapacity( ) to set the size of the buffer.
• They have the following general forms: • This is useful if you know in advance that you will be appending a large
number of small strings to a StringBuffer.
int length( )
• ensureCapacity( ) has this general form:
int capacity( )
void ensureCapacity(int capacity)
• Here, capacity specifies the size of the buffer.
(iii) setLength( )
• To set the length of the buffer within a StringBuffer object, use
setLength( ).
• Its general form is shown here:
void setLength(int len)
• Here, len 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 setLength( ) with a value less than the current value
returned by length( ), then the characters stored beyond the new length
will be lost.
3/6/2025
(iv) charAt( ) and setCharAt( )
• The value of a single character can be obtained
from a StringBuffer via the charAt( ) method.
• You can set the value of a character within a
StringBuffer using setCharAt( ).
• Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
• For charAt( ), where specifies the index of the
character being obtained.
• For setCharAt( ), where specifies the index of
the character being set, and ch specifies the new
value of that character.
• For both methods, where must be nonnegative
and must not specify a location beyond the end
of the buffer.
3/6/2025
(v) getChars( ) (vi) append( )
• To copy a substring of a StringBuffer into an array, use • The append( ) method concatenates the string
the getChars( ) method. representation of any other type of data to the end of the
invoking StringBuffer object.
• General form:
• It has several overloaded versions. A few of its forms are:
void getChars(int sourceStart, int sourceEnd, char
target[ ], int targetStart) StringBuffer append(String str)
• Here, sourceStart specifies the index of the beginning of StringBuffer append(int num)
the substring, and
StringBuffer append(Object obj)
• sourceEnd specifies an index that is one past the end of the
desired substring.
• This means that the substring contains the characters
from sourceStart through sourceEnd–1.
• 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.
• Note: Care must be taken to assure that the target array is
large enough to hold the number of characters in the
specified substring.
3/6/2025
(vii) insert( )
(viii) reverse( )
• The insert( ) method inserts one string into another. • To reverse the characters within a StringBuffer object use
• It is overloaded to accept values of all the simple types, plus reverse( ).
Strings, Objects, and CharSequences.
StringBuffer reverse( )
• It calls String.valueOf( ) to obtain the string representation of the • This method returns the reversed object on which it was called.
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.
3/6/2025
(ix) delete( ) and deleteCharAt( )
• You can delete characters within a StringBuffer
by using the methods delete( ) and
deleteCharAt( ).
StringBuffer delete(int startIndex, int
endIndex)
StringBuffer deleteCharAt(int loc)
• The delete( ) method deletes a sequence of
characters from the invoking object.
• Here, startIndex specifies the index of the first
character to remove, and endIndex specifies an
index one past the last character to remove.
• Thus, the substring deleted runs from startIndex
to endIndex–1. The resulting StringBuffer object
is returned.
• The deleteCharAt( ) method deletes the
character at the index specified by loc. It returns
the resulting StringBuffer object.
3/6/2025
(x) replace( ) • (xi) substring( )
• You can replace one set of characters with another set inside • You can obtain a portion of a
a StringBuffer object by calling replace( ). StringBuffer by calling substring( ).
StringBuffer replace(int startIndex, int endIndex, • It has the following two forms:
String str)
String substring(int startIndex)
• The substring being replaced is specified by the indexes
startIndex and endIndex. String substring(int startIndex, int
endIndex)
• Thus, the substring at startIndex through endIndex–1 is
replaced. • The first form returns the substring
that starts at startIndex and runs to the
• The replacement string is passed in str. end of the invoking StringBuffer
• The resulting StringBuffer object is returned. object.
• The second form returns the substring
that starts at startIndex and runs
through endIndex–1.
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
3/6/2025
Rakesh B S, Dept. of ISE, Vemana IT
STRINGBUILDER
• J2SE 5 adds a new string class to Java’s already powerful string handling capabilities.
• This new class 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 you are using multithreading, you must use
StringBuffer rather than StringBuilder.
3/6/2025