STRING-Module 2 Notes
STRING-Module 2 Notes
VV PURAM BANGALORE
ADVANCED JAVA
NOTES FOR 6TH SEMESTER COMPUTER SCIENCE
PREPARED BY
CHAITHRA G V
ASSISTANT PROFESSOR
TEXT BOOKS
1. Herbert Schildt: Java The Complete Reference, 7th edition, Tata McGraw
Hill, 2007.
2. Uttam k Roy, Adavanced Programming, Oxford University Press.
REFEENCE BOOKS
1
Prepared By: CHAITHRA G V
MODULE -2
STRING HANDLING
STRING
The String, StringBuffer, and StringBuilder classes are defined in java.lang by default
available to all programs automatically.
All are declared final, which means that none of these classes may be subclassed.
All three implement the CharSequence interface.
Once a String object has been created, we cannot perform any changes to the characters
that comprise that string. If we try to perform any changes, a new Object is
created .Hence, String object is Immutable(non-changeable).
str JAVA
str.concate(“DEVELOPER”);
JAVA
str DEVELOPE
System.out.println(str); // JAVADEVELOPER
Once a StringBuffer object is created, we can perform any changes to the characters that
comprises that string. Hence, StringBuffer object is Mutable(changeable).
str.append(“DEVELOPER”);
JAVA
str DEVELOPE
System.out.println(str); // JAVADEVELOPER
2
Prepared By: CHAITHRA G V
The STRING CONSTRUCTOR
STRING LENGTH
3
Prepared By: CHAITHRA G V
String Literals
In the above example, for the String literal abc it creates a String Objects s1.
It calls the length( ) method directly on the string literal "abc".
String Concatenation
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
4
Prepared By: CHAITHRA G V
In the above example, 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.
In the above example, the value 2 is converted into String type. Hence, it
concatenates 3 string four, 2 and 2.
In the above example, the value (2+2) performs the arithmetic Operations and
then converts the result to String type. Hence, it concatenation 2 strings four and
the result 4.
When Java converts data into its string representation during concatenation, it
does so by calling one of the overloaded string conversion method valueOf( )
defined by String
For objects, valueOf( ) calls the toString( ) method on the object.
Every class by default implements toString( ) because it is defined by Object.
The general form of toString( ) method is String toString( ).
Ex:
Class Student
{
int rollno;
String name;
String city;
5
Prepared By: CHAITHRA G V
public static void main(String[] args )
{
Student s1 = new Student(111,”sachin”,”Mumbai”);
Student s1 = new Student(222,”rahul”,”bangalore”);
System.out.println(s1);
System.out.println(s2);
}
}
Student@1fee6fc
Student@1eed786
Class Student
{
int rollno;
String name;
String city;
System.out.println(s1);
System.out.println(s2);
}
}
6
Prepared By: CHAITHRA G V
111 sachin Mumbai
222 rahul Bangalore.
CHARACTER EXTRACTION
charAt( )
getChars( )
It is used to extract a more than one character at a given index from a String.
The general form is
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
sourceStart specifies the index of the beginning of the substring
sourceEnd specifies an index that is one past the end of the desired
substring.
target contains the array of character from sourceStart to sourceEnd–
1.
target specifies the index within the target at which the substring will
be copied.
Ex :
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];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
7
Prepared By: CHAITHRA G V
demo
getBytes( )
STRING COMPARISION
The String class includes a number of methods that compare strings or substrings within
strings.
equals( )
equalsIgnoreCase( )
8
Prepared By: CHAITHRA G V
{
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));
}
}
The output from the program is shown
regionMatches( )
startsWith( )
9
Prepared By: CHAITHRA G V
str is the substring being compared with the given String object.
It returns true if the strings starts with the same characters and same order
in the given string, and false otherwise.
Ex :
endsWith( )
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 to see whether they refer to the
same instance.
class EqualsNotEqualTo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
10
Prepared By: CHAITHRA G V
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
compareTo( )
It is used to check whether the string is greater/lesser than the invoking String
Object. In other words, it checks the string comes before or after the invoking
String Object.
The general form is int compareTo(String str)
str is the String being compared with the invoking String.
Value Meaning
class SortString
{
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[])
{
for(int j = 0; j < arr.length; j++)
{
for(int i = j + 1; i < arr.length; i++)
{
if(arr[i].compareTo(arr[j]) < 0)
{
String t = arr[j];
11
Prepared By: CHAITHRA G V
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
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.
compareToIgnoreCase
It is used to check whether the string is greater/lesser than the invoking String
Object. In other words, it checks the string comes before or after the invoking
String Object.
It is not case sensitive.
The general form is int compareToIgnoreCase(String str)
str is the String being compared with the invoking String.
Value Meaning
class SortString
{
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[])
{
for(int j = 0; j < arr.length; j++)
{
for(int i = j + 1; i < arr.length; i++)
{
if(arr[i].compareToIgnoreCase(arr[j]) < 0)
{
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
SEARCHING STRING
indexOf( )
13
Prepared By: CHAITHRA G V
Case 1: int indexOf(int ch)
Case 2: int indexOf(String str)
Case 3: int indexOf(int ch, int startIndex)
Case 4: int indexOf(String str, int startIndex)
lastIndexOf( )
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.";
System.out.println(s);
14
Prepared By: CHAITHRA G V
System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the",
60));
}
}
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
MODIFYING A STRING
substring( )
class StringReplace
{
public static void main(String args[])
{
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
15
Prepared By: CHAITHRA G V
do
{
System.out.println(org);
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);
}
}
substring( )
String s1 = "one";
String s2 = s1.concat("two"); // puts the string "onetwo" into s2.
replace( )
16
Prepared By: CHAITHRA G V
String s = “hello”;
String str = s.replace(e,E);
trim( )
It is used to copy of the invoking string from which whitespace has been
removed.
The general form is String trim( ).
if(str.equals("Illinois"))
System.out.println("Capital is Springfield.");
else if(str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if(str.equals("California"))
System.out.println("Capital is Sacramento.");
else if(str.equals("Washington"))
System.out.println("Capital is Olympia.");
} while(!str.equals("stop"));
}
}
toLowerCase( )
17
Prepared By: CHAITHRA G V
It is used to converts all the characters in a string from uppercase to lowercase.
The general form is String toLowerCase( )
toUpperCase( )
class ChangeCase
{
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
JOINING STRINGS
It is used to concatenate two or more strings, separating each string with a delimiter, such
as a space or a comma.
The general form is static String join(CharSequence delim, CharSequence . . . strs)
specifies the delimiter used to separate the character sequences specified by strs.
Ex :
class StringJoinDemo
{
public static void main(String args[])
{
String result = String.join(" ", "Alpha", "Beta", "Gamma");
System.out.println(result);
18
Prepared By: CHAITHRA G V
result = String.join(", ", "John", "ID#: 569","E-mail: John@HerbSchildt.com");
System.out.println(result);
}
}
In the first call to join( ), a space is the delimeter and inserted between each string.
In the second call, the delimiter is a comma followed by a space.
Delimiter need not be just a single character.
METHOD MEANING
specified by i.
19
Prepared By: CHAITHRA G V
str) Otherwise, returns false.
20
Prepared By: CHAITHRA G V
result. Each part is delimited by the
regular expression passed in
regExp.
STRINGBUFFER
StringBuffer represents fixed-length, immutable character
sequences and modifiable string.
It represents growable and writable.
It may have characters and substrings inserted in the middle or
appended to the end.
STRINGBUFFER CONSTRUCTOR
21
Prepared By: CHAITHRA G V
Creates an empty string using new operator with default capacity 16.
Once its reaches its maximum capacity then a new StringBuffer object will be
created with new_capacity = (current_capacity+1)*2.
The performance decreases with the default capacity. To overcome the above
problem, StringBuffer object with intial capacity was created.
If we know the initial capacity in advance, then StringBuffer object with intial
capacity is used. Hence the performance of the system increases.
For the given string literal str an equivalent stringBuffer object is created.
The capacity of StringBuffer s is length of str + capacity of s.
Ex :
length( )
capacity( )
It is used to find the current capacity of StringBuffer.
The general form is int capacity( ).
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
22
Prepared By: CHAITHRA G V
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
The output of this program is:
buffer = Hello
length = 5
capacity = 21
Since sb is initialized with the string "Hello" when it is created, its length
is 5.
Its capacity is 21 because room for 16 additional characters is
automatically added.
ensureCapacity( )
It is used to to preallocate room for a certain number of characters after a
StringBuffer has been constructed.
The general form is void ensureCapacity(int minCapacity).
minCapacity specifies the minimum size of the buffer.
setLength( )
charAt( )
23
Prepared By: CHAITHRA G V
The value of index must be nonnegative and specify a location within the
string.
// Demonstrate charAt() and setCharAt().
class setCharAtDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
The output generated by this program:
getChars( )
It is used to concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object.
The general form is
Case 1: StringBuffer append(String str)
Case 2: StringBuffer append(int num)
Case 3: StringBuffer append(Object obj)
The string representation of each parameter is obtained, often by calling
String.valueOf( ).
24
Prepared By: CHAITHRA G V
// Demonstrate append().
class appendDemo
{
public static void main(String args[])
{
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
The output of this example is shown here:
a = 42!
insert( )
// Demonstrate insert().
class insertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
reverse( )
25
Prepared By: CHAITHRA G V
Demonstrates reverse( ):
class ReverseDemo
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
delete( )
deleteCharAt( )
class deleteDemo
{
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(0);
System.out.println("After deleteCharAt: " + sb);
}
26
Prepared By: CHAITHRA G V
}
replace( )
It is used to replace one set of characters with another set inside a StringBuffer
object
The general form is replace(int startIndex, int endIndex, String str)
startIndex specifies the index of the first character.
endIndex specifies an index one past the last character.
The substring at startIndex through endIndex–1 is replaced.
Ex :
// Demonstrate replace( )
class replaceDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
The output:
After replace: This was a test.
substring( )
specified by i.
int indexOf(String str, int startIndex) Searches the invoking StringBuffer for the
first occurrence of str, beginning at
startIndex. Returns the index of the match, or
–1 if no match is found.
int lastIndexOf(String str, int Searches the invoking StringBuffer for the
startIndex) last occurrence of str, beginning at
startIndex. Returns the index of the match, or
. –1 if no match is found.
28
Prepared By: CHAITHRA G V
specified by start.
29
Prepared By: CHAITHRA G V