PAGE-8

CHAPTER-2(Classes and Objects)                                   BOTTOM

 

String Class:-

In Java a string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String.String is a class defined in java.lang package and has various methods that make the string handing convenient .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.

When you create a String object, we 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.At first, this may seem to be a serious restriction. However, such is not the case. 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.there is a companion class to String called StringBuffer, whose objects contain strings that can bemodified after they are created.

Both the String and StringBuffer classes are defined in java.lang. Thus, they are available to all programs automatically. Both are declared final, which means that neither of these classes may be subclassed.



 

Special String Operations:-

 

String Concatination:-


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.

For example, the following fragment concatenates three strings:


String age = "15";
String s = "He is " + age + " years old.";
System.out.println(s);

This displays the string “He is 15 years old.”

 

Character Extraction

The String class provides a number of ways in which characters can be extracted from a String object. Although the characters that comprise a string many of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero.


charAt( )


To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. It has this general form:

Syntax :-

char charAt(int where)

Here, where is the index of the character that you want to obtain.The value of where must be nonnegative and specify a location within the string. charAt( ) returns the character at the specified location. For example,

char ch;
ch = "man".charAt(1);
assigns the value “a” to ch.

 

getChars( )


If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form:-

Syntax:-

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. The following program demonstrates getChars( ):


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);
}
}

Here is the output of this program:-

demo

String Comparison

The String class includes several methods that compare strings or substrings within strings. Each is examined here.

equals( ) and equalsIgnoreCase( )


To compare two strings for equality, use equals( ). It has this general form:

Syntax:-

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, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:

Syntax:-

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.

Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
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));
}
}

The output from the program is shown here:

Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

 

equals( ) Versus ==


It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, 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. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}

Output:-

Hello equals Hello -> true
Hello == Hello -> false

Searching Strings


The String class provides two methods that allow you to search a string for a specified character or substring:
indexOf( ) Searches for the first occurrence of a character or substring.
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.
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.
The following example shows how to use the various index methods to search inside of Strings:

// Demonstrate indexOf() and 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);
System.out.println("indexOf(t) = " + s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " + s.indexOf("the"));
System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}


Here is the output of this 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

 

Modifying a String


Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the string with your modifications complete.


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. The following program uses substring( ) to replace all instances of one substring with another within a string:


// Substring replacement.

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;
do {       // replace all matching substrings
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);
}
}


The output from this program is shown here:-

This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

 

String Buffer

 

StringBuffer is a peer class of String that provides much of the functionality of strings. As you know, 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. StringBuffer 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.

Methods used by String Buffer

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.Following example shows the use of setLength method along with charAt( ) and setCharAt( )

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.

The following example demonstrates charAt( ) and setCharAt( ):

// 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));
}
}

Here is the output generated by this program:

buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i

 

append( )

The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms:

StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example:


// Demonstrate append().
class appendDemo {
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer();
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}


The output of this example is shown here:
a = 42!

insert( )


The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls . 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.
The following sample program inserts “like” between “I” and “Java”:

// Demonstrate insert().
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}

The output of this example is shown here:

I like Java!

delete( ) and deleteCharAt( )


Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and deleteCharAt( ). These methods are shown here:

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. Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:

// Demonstrate delete() and 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);
}
}

The following output is produced:

After delete: This a test.
After deleteCharAt: his a test.

replace( )


Another method added to StringBuffer by Java 2 is replace( ). It replaces one set of characters with another set inside a StringBuffer object. Its signature is shown here: StringBuffer replace(int startIndex, int endIndex, String str) The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.
The following program demonstrates replace( ):

// 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);
}
}

Here is the output:-

After replace: This was a test.

 



Note :
After Successful completion of Training Candidate will be provided with Project Report and Training Certificate.

Home  |   FeedBack  |   Terms of Use  |   Contact Us  |   Report Error
                                                                            Copyright 2009 R.M Infotech (P) Ltd.                                             Designed by: Raman