Module 2 String Handling
Module 2 String Handling
STRING HANDLING
Overview of the Module
• 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
2
String Handling- Introduction
• Like many other programming languages, a string is a sequence of
characters.
• Unlike some other languages that implement strings as character
arrays, Java implements strings as objects of type String.
• Implementing strings as built-in objects allows Java to provide a full
complement of features that make string handling convenient- Java
has a variety of methods for different string operations.
• String objects are immutable - a string that cannot be changed.
• If modifiable string is desired then classes StringBuffer and
StringBuilder can be used.
• The String, StringBuffer, and StringBuilder classes are defined in
[Link]. Thus, they are available to all programs automatically.
• All are declared final, which means that none of these classes may be
subclassed.
3
String Constructors
String class supports several constructors.
1. To create an empty String call the default Constructor.
String s = new String();
will create an instance of String with no characters in it.
5
String Constructors
4. We can construct a String object that contains the same
character sequence as another String object using the following
constructor
String(String strObj)
Here, strObj is a String object.
Example: Copy a String object sequence to another:
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
[Link](s1);
[Link](s2);
}
}
The output from this program is as follows:
Java
Java 6
String Constructors
5. constructors to create a string when given a byte array
• Though Java’s char type uses 16 bits to represent the Unicode
Character Set, typical strings on internet uses arrays of 8-bits byte
codes constructed from ASCII set.
• Because 8-bit ASCII strings are common ,Strings provides constructors
to create a string when given a byte array.
• The Two forms are shown here:
String(byte chrs[ ])
String(byte chrs[ ], int startIndex, int numChars)
Here, chrs 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.
Example-> next slide 7
String Constructors
Example:
class SubStringCons{
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
[Link](s1);
String s2 = new String(ascii, 2, 3);
[Link](s2);
}
}
This program generates the following output:
ABCDEF
CDE
8
String Constructors
6. You can construct a String from a StringBuffer by using the
constructor shown here:
String(StringBuffer strBufObj)
9
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:
Syntax: int length( )
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
[Link]([Link]());
10
Special String Operations
• Java has added special support for several string operations within
the syntax of the language-
➢ automatic creation of new String instances from string literals
➢ concatenation of multiple String objects by use of the + operator
➢ the conversion of other data types to a string representation
❖ Explicit methods are available in Java to perform all of these
functions, but Java does them automatically as a convenience for the
programmer and to add clarity.
String Literals
• We can create a String instance using literals. For every literals in the
program, Java automatically constructs a String object.
String s= “sample string”; //using string literal; no new keyword
• Since String object is created for every literal string, we can use a
string literal in any place where a String object can be used.
[Link](“abc”.length()); 11
Special String Operations
String Concatenation
• Java does not allow operators to be used on Strings.
• One exception to this rule is the + operator, which can be used to
concatenate two strings
Example: String age = "9";
String s = "He is " + age + " years old.";
[Link](s);
• One of its most common usage is when creating a long strings.
// Using concatenation to prevent long lines.
class ConCat {
public static void main(String[] args) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
[Link](longStr);
}
12
}
Special String Operations
String Concatenation with other data types
• Java allows to concatenate strings with other data types.
Example: int age = 9;
String s = "He is " + age + " years old.";
[Link](s);
• Have to be careful when mixing multiple operations
String s= “four: ”+ 2 + 2;
[Link](s);
This fragment displays four: 22, rather than the four: 4
Example
String str = [Link](10);
[Link]("string value= "+str);
14
Special String Operations
String Conversion and toString() Contd..
• Every class implements toString( ) because it is defined by Object.
• We can provide our own string representation for objects of classes
by overriding toString( ).
• toString() has the general form
String toString()
• To implement toString( ), simply return a String object that contains
the human-readable string that appropriately describes an object of
your class.
• When the classes are crteated, we will have to override toString() to
provide the string representations.
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
[Link](b); // convert Box to string
[Link](s);
}
}
17
Character Extraction
String class provides several methods to extract characters from a String
object.
• Though the characters within a String object cannot be indexed like
character arrays, many of String methods employ an index approach for
their operations.
Note:
• sourceStart specifies the index of the beginning of the substring.
• sourceEnd specifies an index that is one past the end of the desired
substring.
• 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.
19
Character Extraction
getChars() Example:
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
[Link](start, end, buf, 0);
[Link](buf);
}
}
output:
demo
20
Character Extraction
3. getBytes()
• getBytes() method is an alternative to getChars() and stores the
characters in an array of bytes.
• Uses the default character-to-byte conversions
• General form: byte[] getBytes()
• Useful in platforms which does not support 16-bit Unicode
characters.
4. toCharArray()
• Converts all the characters in a String object into character array. It
has this general form: char[ ] toCharArray( )
String s=“JAVA PROGRAMMING";
char msg[]=new char[50];
msg = [Link]();
[Link](msg); 21
String Comparison
• String class includes several methods to compare strings or substrings
within strings.
1. equals() and equalsIgnoreCase()
• To compare two strings for equality, use equals( ). It has this general
form: boolean equals(Object str)
• Here, str is the String object being compared with the invoking String
object. It returns true if the strings contain the same characters in the
same order, and false otherwise. The comparison is case-sensitive.
• To perform a comparison that ignores case differences, we can use
equalsIgnoreCase( ). When it compares two strings, it considers A-Z
to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
• Here, str is the String object being compared with the invoking String
object. It, too, returns true if the strings contain the same characters
in the same order, and false otherwise.
22
String Comparison
class equalsDemo {
public static void main(String args[]) {
String s1 = “Hello";
String s2 = “Hello ";
String s3 = “Welcome";
String s4 = “HELLO";
[Link](s1 + " equals " + s2 + " -> " +[Link](s2));
[Link](s1 + " equals " + s3 + " -> " +[Link](s3));
[Link](s1 + " equals " + s4 + " -> " +[Link](s4));
[Link](s1 + " equalsIgnoreCase " + s4 + " -> "
+[Link](s4));
}
}
Output:
Hello equals Hello -> true
Hello equals Welcome -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
23
String Comparison
2. regionMatches()
• This method compares a specific region inside a string with another
specific region in another string.
General form:
1. boolean regionMatches(int startIndex, String str2,
int str2StartIndex, int numChars)
2. boolean regionMatches(boolean ignoreCase, int startIndex ,
String str2, int str2StartIndex, int numChars)
27
String Comparison
A sample program that sorts an array of strings. The program uses
compareTo( ) to determine sort ordering for a bubble sort:
class StringSorting {
public static void main(String args[]) {
String str[] = {“Sachin",“Dravid",“Srinath",“Kumble",“Anil",“Rahul"};
for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (str[i].compareTo(str[j]) > 0) {
String t = str[i]; OUTPUT
str[i] = str[j]; Sorted strings are..
str[j] = t; Anil
} Dravid
Kumble
}
Rahul
} Sachin
[Link]("Sorted names are.."); Srinath
for (int i = 0; i < [Link]; i++)
[Link](str[i]); } } } 28
String Comparison
5. compareToIgnoreCase()
• If you want to ignore case differences when comparing two
strings, use compareToIgnoreCase( ) method.
int compareToIgnoreCase(String str)
• This method returns the same results as compareTo( ), except
that case differences are ignored.
29
Searching Strings
• String class provides two methods to search a string for a specified
character or substring.
1. indexOf() : Searches for the first occurrence of a character or
substring
2. lastIndexOf() : Searches for the last occurrence of a character or
substring
• 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 –1 on failure.
• To search for the first occurrence of a character, use
int indexOf(int ch)
• To search for the last occurrence of a character, use
int lastIndexOf(int ch)
Here, ch is the character being sought.
30
Searching Strings
• To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
Here, str specifies the substring.
• You 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.
• For indexOf( ), the search runs from startIndex to the end of the
string.
• For lastIndexOf( ), the search runs from startIndex to zero. 31
Searching Strings
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
[Link](s);
[Link]("indexOf(t) = " +[Link]('t'));
[Link]("lastIndexOf(t) = " +[Link]('t'));
[Link]("indexOf(the) = " +[Link]("the"));
[Link]("lastIndexOf(the) = " +[Link]("the"));
[Link]("indexOf(t, 10) = " +[Link]('t', 10));
[Link]("lastIndexOf(t, 60) = " +[Link]('t', 60));
[Link]("indexOf(the, 10) = " +[Link]("the", 10));
[Link]("lastIndexOf(the, 60) = " +[Link]("the", 60));
}
}
32
Searching Strings
Here is the output of the program:
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
33
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 a String method that constructs a new copy of
the string with your modifications complete.
substring()
This method extracts a substring from a string. It has two forms.
1. 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.
2. 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.
34
Modifying a String
public class substringDemo {
public static void main(String [] args) {
String str="Java Programming is Exciting";
String s1=[Link](5);
String s2=[Link](5, 16);
[Link]("First string s1= "+s1);
[Link]("Second string s2 ="+s2);
}
}
Output
First string s1= Programming is Exciting
Second string s2 =Programming
35
Modifying a String
concat() :
• This method concatenates two strings
String concat(String str)
• This method creates a new object that contains the invoking
string with the contents of str appended to the end.
Example:
String s1 = "one";
String s2 = [Link]("two");
36
Modifying a String
replace()
• This method replaces a specific character or a string in the invoking
string. The replace( ) method has two forms.
• The first replaces all occurrences of one character in the invoking
string with another character.
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character
specified by replacement. The resulting string is returned.
38
Modifying a String
trim( ) and strip( ) contd..
• Beginning with JDK 11, Java also provides the methods strip( ),
stripLeading( ), and stripTrailing( ).
• The strip( ) method removes all whitespace characters (as defined
by Java) from the beginning and end of the invoking string and
returns the result. Such whitespace characters include, among
others, spaces, tabs, carriage returns, and line feeds.
• The stripLeading( ) method delete whitespace characters from the
start of the invoking string and return the result.
• The stripTrailing( ) method delete whitespace characters from the
end of the invoking string and return the result.
• strip( ) handles all Unicode whitespace characters, which may
include characters not considered whitespace by the trim() method.
This makes strip() more robust for different text encodings.
39
Data Conversion using valueOf()
• The valueOf() method converts the data from internal format to
human-readable format.
• It is a static method that is overloaded within String for all of Java’s
built-in types so that each type can be converted properly into a
string.
• valueOf( ) is also overloaded for type Object, so an object of any
class type you create can also be used as an argument.
• valueOf() method has the following forms:
1. static String valueOf(double num)
2. static String valueOf(long num)
3. static String valueOf(Object obj)
4. static String valueOf(char chars[])
5. static String valueOf(char chars[], int startIndex, int numChars)
40
Data Conversion using valueOf()
• As discussed earlier, valueOf( ) 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 String representation. 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. In fact, you could just call toString( )
directly and get the same result.
• 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.
41
Changing the Case of Characters Within a String
• The method toLowerCase() converts all the characters in a string
from upper to lowercase and the method toUpperCase()
performs vice versa.
String toLowerCase()
String toUpperCase()
• Both methods returns a String object containing the altered case
string.
Example:
String str = "This is a test.";
String upper = [Link]();
String lower = [Link]();
42
Changing the Case of Characters Within a String
Program Example:
class ChangeCase {
public static void main(String args[]){
String s = "This is a test.";
[Link]("Original: " + s);
String upper = [Link]();
String lower = [Link]();
[Link]("Uppercase: " + upper);
[Link]("Lowercase: " + lower);
}
}
44
Joining Strings
Example Program:
class StringJoinDemo {
public static void main(String args[]) {
String result = [Link](" ", "Alpha", "Beta", "Gamma");
[Link](result);
result = [Link](", ", "John", "ID#: 569", "E-mail:
John@[Link]");
[Link](result);
}
}
46
Additional String Methods
47
StringBuffer
• StringBuffer is a peer class of String and provides much of the
functionality of strings. StringBuffer supports a modifiable string.
• As we know String are fixed-length ,immutable character
sequences. In contrast, StringBuffer represents growable and
rewriteable character sequences.
• StringBuffer may have characters and substrings inserted in the
middle or appended to the end.
• StringBuffer will automatically grow to make room for such
additions
48
StringBuffer
StringBuffer Constructors: StringBuffer defines the following
four constructors:
• StringBuffer() - Default constructor, reserves room for 16 characters
without reallocation
• StringBuffer(int size) - accepts an integer argument that explicitly
sets the size of the buffer.
• StringBuffer(String str) - accepts a String argument that sets the
initial contents of the StringBuffer object and reserves room for 16
more characters without reallocation.
• StringBuffer(CharSequence chars) - creates an object that contains
the character sequence contained in chars.
Note: StringBuffer 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, StringBuffer reduces the number
of reallocations that take place. 49
StringBuffer Methods
length() and capacity()
• Current length of a StringBuffer can be found via the length() method.
• The total allocated capacity can be found through the capacity()
method.
• General form: int length()
int capacity()
Example:
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());
[Link]("capacity = " +[Link]());
}
the output of this program
}
buffer = Hello
length = 5
50
capacity = 21
StringBuffer Methods
ensureCapacity()
• If we want to preallocate room for a certain number of characters
after a StringBuffer has been constructed , we can use
ensureCapacity() to set the size of the buffer.
• General form: void ensureCapacity(int minCapacity)
Here, minCapacity specifies the minimum size of the buffer. (A buffer
larger than minCapacity may be allocated for reasons of efficiency.)
StringBuffer sb = new StringBuffer("sampletext");
[Link]("buffer = " + sb);
[Link]("Old Capacity = " + [Link]());
[Link](28);
[Link]("New Capacity = " + [Link]());
Output:
buffer = sampletext
Old Capacity = 26
51
New Capacity = 54
StringBuffer Methods
setLength()
• Used to set the length of the string within a StringBuffer object.
• General form:
void setLength(int len)
• 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 buffer
• If the value less than the current value returned by length( ), then
the characters stored beyond the new length will be lost.
52
StringBuffer Methods
charAt() and setCharAt()
• A single character can be obtained from a StringBuffer using
charAt() method
• General form: char charAt(int where)
53
StringBuffer Methods
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer before = " + sb);
[Link]("charAt(1) before="+ [Link](1));
[Link](1, 'i');
[Link](2);
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " + [Link](1));
}
}
Example:
class getCharsDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer(“This is a demo of”);
int start = 10;
int end = 14;
char buf[] = new char[end - start];
[Link](start, end, buf, 0);
[Link](buf);
}
}
55
StringBuffer Methods
append()
• Concatenates the string representation of any other type of data to
the end of invoking StringBuffer object.
• General form: StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
[Link]( ) is called for each parameter to obtain its string
representation.
Example:
String s;
int a = 32;
StringBuffer sb = new StringBuffer(40);
s =[Link]("My age is = ").append(a).toString();
[Link](s);
// toString() required to convert StringBuffer to String
Output:
My age is = 32 56
StringBuffer Methods
append() contd..
Note:
• The append( ) method is most often called when the + operator
is used on String objects.
• Thus, a concatenation invokes append( ) on a StringBuffer object.
• After the concatenation has been performed, the compiler
inserts a call to toString( ) to turn the modifiable StringBuffer
back into a constant String.
57
StringBuffer Methods
insert()
• This method 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 [Link]( ) to obtain the string
representation of the value it is called with.
• General form: StringBuffer insert (int index, String str)
StringBuffer insert (int index, char ch)
StringBuffer insert (int index, Object obj)
Example:
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java");
[Link](2, "like ");
[Link](sb); Output:
58
}} I like Java
StringBuffer Methods
reverse()
• Used to reverse the characters within a StringBuffer object.
• General form: StringBuffer reverse()
This method returns the reverse of the object on which it was called.
Example:
class ReverseDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("ABCD");
[Link]("Before Reverse: " + sb);
[Link]();
[Link]("After Reverse: "+ sb); }
}
Output:
Before Reverse: ABCD
After Reverse: DCBA 59
StringBuffer Methods
delete() and deleteCharAt()
• Use to Delete the characters within a StringBuffer object.
• General form: StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
Example:
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
[Link](4, 7);
[Link]("After delete: " + sb);
[Link](0);
[Link]("After deleteCharAt: " + sb);
} Output:
} After delete: This a test.
After deleteCharAt: his a test. 60
StringBuffer Methods
replace()
• Used to Replace one set of characters with another set inside a
StringBuffer object.
• General form:
StringBuffer replace(int startIndex, int endIndex, String str)
• The substring at startIndex through endIndex–1 is replaced.
Example:
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
[Link](5, 7, "was");
[Link]("After replace: " + sb);
}
Output:
}
After replace: This was a test. 61
StringBuffer Methods
substring()
• We can obtain a portion of a StringBuffer by calling substring( )
• General form: String substring(int startIndex)
String substring(int startIndex, int endIndex)
• The first form returns the substring that starts at startIndex and runs
to the end of the invoking StringBuffer object.
• The second form returns the substring that starts at startIndex and
runs through endIndex–1.
Example:
StringBuffer sb = new StringBuffer("This is a sample text");
String sub1=[Link](5);
String sub2=[Link](10, 16);
[Link](“sub1: "+sub1);
[Link](“sub2: "+sub2);
Output:
sub1: is a sample text
sub2: sample 62
Additional StringBuffer Methods
63
StringBuffer Methods
The following program demonstrates indexOf( ) and lastIndexOf( ):
class IndexOfDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("one two one");
int i;
i = [Link]("one");
[Link]("First index: " + i);
i = [Link]("one");
[Link]("Last index: " + i);
}
}
64
StringBuilder
• Introduced in JDK 5 as a recent addition to Java’s string handling
capabilities.
• StringBuilder is similar 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.
• In cases in which a mutable string will be accessed by multiple
threads, and no external synchronization is employed, you must
use StringBuffer rather than StringBuilder.
65
Exercise- Java Programs
• Explain various constructors provided by String class
with example programs.
• Write a program that describes substring(), trim(),
replace() and change of case of characters in String
class.
• Discuss the difference between equals() versus ==
with suitable example program.
• Write a program to read and sort the strings in
ascending order.
• What is StringBuffer class? Explain the constructors
of StringBuffer class with example programs.
• Explain append(),insert(), reverse(),delete() ,
indexOf(), lastIndexOf() methods with sample Java
programs.
66
Exercise- Java Programs
1. Java program to count number of words in a
sentence.
2. Java program to extract words from a line of text
and print the words and their lengths.
3. Java program to count number of vowels in a
sentence.
4. Java program to delete a word in a sentence.
5. Java program to count number of digits, alphabets
in a line of text.
67
end
68