unit 4 java as oop language string handling · 2017-02-28 · about string in java • java...

42
Unit 4 Java as OOP Language String Handling

Upload: others

Post on 11-Aug-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Unit 4Java as OOP Language

String Handling

Page 2: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

About String in JAVA

• Java implements strings as objects of type String.

• String objects can be constructed a number of ways, making it easy to obtain a string when needed.

• 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.

• 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.

• The String, StringBuffer, and StringBuilder classes are defined in java.lang and are declared final. All three implement the CharSequence interface.

• However, a variable declared as a String reference can be changed to point at some other String object at any time.

Page 3: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

The String ConstructorsThe String class supports several constructors.

• String s = new String(); //create an empty String

• String(char chars[ ]) //create a String initialized by an array of characters

– char chars[] = { 'a', 'b', 'c' };

– String s = new String(chars); //initializes s with the string "abc".

You can specify a subrange of a character array as an initializer

• String(char chars[ ], int startIndex, int numChars)

– char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

– String s = new String(chars, 2, 3); //initializes s with the characters cde.

• String(String strObj) //construct a String object that contains the same character sequence as another String object

Page 4: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

As 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform.

String(byte chrs[ ])String(byte chrs[ ], int startIndex, int numChars)

Eg:// Construct string from subset of char array.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); }}

You can construct a String from a StringBuffer and from a StringBuilder by using the constructor shown here:

String(StringBuffer strBufObj)String(StringBuilder strBuildObj)

Page 5: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

String Length• The length of a string is the number of characters that it contains.

• int length( )

Eg :

char chars[] = { 'a', 'b', 'c' };

String s = new String(chars);

System.out.println(s.length());

o/p-3

Page 6: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Special String Operations• Java has added special support for several string operations like the

automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation.

a) String Literals

•) The earlier examples showed how to explicitly create a String instance from an array of characters by using the new operator.

•) However, there is an easier way to do this using a string literal.

•) For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object.

char chars[] = { 'a', 'b', 'c' };

String s1 = new String(chars);

String s2 = "abc"; // use string literal

Page 7: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

• you can use a string literal any place you can use a String object.System.out.println("abc".length());

B) 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.

String age = "9";

String s = "He is " + age + " years old.";

System.out.println(s);

o/p- "He is 9 years old.“

• One practical use of string concatenation is found when you are creating very long strings.

Page 8: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Eg:

// 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.";System.out.println(longStr);} }

c) String Concatenation with Other Data Types : You can concatenate strings with other types of data.

Page 9: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Eg: int age = 9;String s = "He is " + age + " years old.";System.out.println(s);

• The int value in age is automatically converted into its string representation within a String object

• Be careful when you mix other types of operations with string concatenation expressions.

String s = "four: " + 2 + 2;System.out.println(s);

o/p - four: 22

• To complete the integer addition first, you must use parenthesesString s = "four: " + (2 + 2);

o/p - four: 4

Page 10: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

String Conversion and toString( )• When Java converts data into its string representation during

concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String.

• valueOf( ) is overloaded for all the primitive types and for type Object• For the primitive types, valueOf( ) returns a string that contains the

human-readable equivalent of the value with which it is called.• For objects, valueOf( ) calls the toString( ) method on the object.• Every class implements toString( ) because it is defined by Object.

However, the default implementation of toString( ) is seldom sufficient.• The toString( ) method has this 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.

Page 11: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Eg:// Override toString() for Box class.class Box {double width;double height;double 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 toStringDemo {public static void main(String args[]) {Box b = new Box(10, 12, 14);String s = "Box b: " + b; // concatenate Box objectSystem.out.println(b); // convert Box to stringSystem.out.println(s);}}

The output :Dimensions are 10.0 by 14.0 by 12.0Box b: Dimensions are 10.0 by 14.0 by 12.0

Box’s toString( ) method is automatically invoked when a Box object isused in a concatenation expression or in a call to println( ).

Page 12: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Character Extraction• a String object cannot be indexed as if they were a character array, many

of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero.

A) charAt( ) : To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method.

char charAt(int where)

•) The value of where must be nonnegative and specify a location within the string.

char ch;

ch = "abc".charAt(1);

B) getChars( ) : If you need to extract more than one character at a time, you can use the getChars( ) method.

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

Page 13: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

• 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. (Substring is from sourceStart through sourceEnd–1.)

Eg:

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

}

O /p - demo

Page 14: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

C) getBytes( ) : There is an alternative to getChars( ) that stores the characters in an array of bytes. Method is getBytes(). There is an alternative to getChars( ) that stores the characters in an array of bytes.

byte[ ] getBytes( )

D) toCharArray( ) : to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string.

char[ ] toCharArray( )

• This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result.

Page 15: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

String ComparisonA) equals( ) and equalsIgnoreCase( ):

To compare two strings for equality, use equals( ).

boolean equals(Object str)

•) 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( ).

boolean equalsIgnoreCase(String str)

Page 16: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

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

}}

o/p- Hello equals Hello -> trueHello equals Good-bye -> falseHello equals HELLO -> falseHello equalsIgnoreCase HELLO -> true

Page 17: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

B) 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.

boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)

boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)

• 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.

Page 18: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

C) startsWith( ) and endsWith( ) :• These Methods are specialized forms of regionMatches( ).• The startsWith( ) method determines whether a given String begins with

a specified string. Conversely, 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 the string matches, true is returned. Otherwise, false is returned.

"Foobar".endsWith("bar") //true"Foobar".startsWith("Foo") //true

• A second form of startsWith( )boolean startsWith(String str, int startIndex)

• startIndex specifies the index into the invoking string at which point the search will begin.

"Foobar".startsWith("bar", 3) //true

Page 19: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

D) equals( ) Versus ==• 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.

Eg: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));

}}O/p- Hello equals Hello -> true

Hello == Hello -> false

Page 20: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

E) compareTo( ) : • it is not enough to simply know whether two strings are identical. For

sorting applications, you need to know which is less than, equal to, or greater than the next.

• A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order.

• The method compareTo( ) serves this purpose. It is specified by the Comparable<T> interface, which String implements.

int compareTo(String str)• The result of the comparison is returned and is interpreted as shown here:Value MeaningLess than zero The invoking string is less than str.Greater than zero The invoking string is greater than str.Zero The two strings are equal.

int compareToIgnoreCase(String str)

Page 21: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Eg: // A bubble sort for Strings.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]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } }

Page 22: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

The output of this program is the list of words: Now aid all come country for good is men of the the their time to to

Page 23: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

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 or last occurrence of a substring

int indexOf(String str)

int lastIndexOf(String str)● 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)

Page 24: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

● For indexOf( ), the search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs from startIndex to zero.

● Eg:

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

Page 25: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

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

O/p- 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

Page 26: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

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 tring method that constructs a new copy of the string with your modifications complete.

a) substring( ) : extract a substring using substring( ).● It has two forms.

String substring(int startIndex) // returns a copy of the substring that begins at startIndex and runs to the end of the invoking string.String substring(int startIndex, int endIndex) // specify both the beginning and ending index (excluding last index char)

b) concat( ) : concatenate two strings using concat( )● String concat(String str)● This method creates a new object that contains the invoking string with the

contents of str appended to the end. concat( ) performs the same function as +.

Page 27: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

String s1 = "one";String s2 = s1.concat("two"); //puts the string "onetwo" into s2

● It generates the same result as the following sequenceString s1 = "one";String s2 = s1 + "two";

c) replace( ) : The replace( ) method has two forms.● String replace(char original, char replacement) //replaces all occurrences

of one character in the invoking string with another character.Eg :

String s = "Hello".replace('l', 'w');● String replace(CharSequence original, CharSequence replacement)

//replaces one character sequence with another.

d) trim( ) : method returns a copy of the invoking string from which any leading and trailing whitespace has been removed.

● String trim( )Eg: String s = " Hello World ".trim(); //puts the string "Hello World"

into s.

Page 28: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

● The trim( ) method is quite useful when you process user commands. For example, the program may prompts the user for the name of a state and then displays that state’s capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

Assignment : Demonstrate working of function valueOf( ) with the help of example.

Page 29: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

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.String toLowerCase( )String toUpperCase( )

● Eg:String s = "This is a test."; System.out.println("Original: " + s);String upper = s.toUpperCase(); System.out.println("Original: " + s);String lower = s.toLowerCase(); System.out.println("Original: " + s);

Page 30: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Joining Strings

● JDK 8 adds a new method to String called join( ).● It is used to concatenate two or more strings, separating each string with a

delimiter, such as a space or a comma. ● static String join(CharSequence delim, CharSequence . . . strs)

// delim specifies the delimiter used to separate the character sequencesspecified by strs. Because String implements the CharSequence interface, strs can be a list of strings

● Eg : String result = String.join(" ", "Alpha", "Beta", "Gamma");System.out.println(result);result = String.join(", ", "John", "ID#: 569","E-mail: [email protected]");System.out.println(result);O/p- Alpha Beta Gamma //delimiter is space

John, ID#: 569, E-mail: [email protected] //deliniter is ,

Page 31: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

Additional String Methods

● int codePointAt(int I)● int codePointBefore(int I)● int codePointCount(int start, int end)● boolean contains(CharSequence str)● boolean contentEquals(CharSequence str)● boolean contentEquals(StringBuffer str)● static String format(String fmtstr, Object ... args)● static String format(Locale loc,String fmtstr,Object ... args)● boolean isEmpty( )● boolean matches(string regExp)● int offsetByCodePoints(int start, int num)● String replaceFirst(String regExp,String newStr)● String replaceAll(String regExp, String newStr)● String[ ] split(String regExp)● String[ ] split(String regExp, int max)● CharSequence subSequence(int startIndex, int stopIndex)

Page 32: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

StringBuffer

● StringBuffer supports a modifiable string. ● StringBuffer represents growable and writable 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.

● StringBuffer defines these four constructors: StringBuffer( ) StringBuffer(int size) StringBuffer(String str) StringBuffer(CharSequence chars)

● The default constructor (the one with no parameters) 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.

Page 33: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

● The fourth constructor creates an object that contains the character sequence contained in chars and reserves room for 16 more characters.

● StringBuffer allocates room for 16 additional characters , because: – reallocation is a costly process in terms of time. – frequent reallocations can fragment memory. – It reduces the number of reallocations that take place

Page 34: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

a) length( ) and capacity( ) :● The current length of a StringBuffer can be found via the length( ) method,

while the total allocated capacity can be found through the capacity( ) method.

int length( ) int capacity( )Eg: // StringBuffer length vs. capacity.class StringBufferDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer = " + sb); System.out.println("length = " + sb.length()); System.out.println("capacity = " + sb.capacity()); } }

O/P- buffer = Hello length = 5 capacity = 21

Page 35: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

b) ensureCapacity( ) : This method is used to preallocate room for a certain number of characters after a StringBuffer has been constructed.

● It set the minimum size of the buffer.void ensureCapacity(int minCapacity)

//minCapacity specifies the minimum size of the buffer.

c) setLength( ) : To set the length of the string within a StringBuffer object

void setLength(int len)

// len specifies the length of the string. This value must be nonnegative.

● When we increase the size of the string, null characters are added to the end.

● If we call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.

Page 36: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

d) 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( ).

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 string.

e) getChars( ) : To copy a substring of a StringBuffer into an array, use the getChars( ) method.void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

● Here, sourceStart specifies the index of the beginning of the substring, and sourceEndspecifies 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.

Page 37: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

f) append( ) : The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object.

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

● The string representation of each parameter is obtained, often by calling String.valueOf( ).

● The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together.

Eg : 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);}O/P- a = 42!

Page 38: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

g) insert( ) : The insert( ) method inserts one string into another. It is overoaded to accept values of all the primitive types, plus Strings, Objects, and CharSequences. Like append( ), it obtains the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object.

StringBuffer insert(int index, String str)StringBuffer insert(int index, char ch)StringBuffer insert(int index, Object obj)

● index specifies the index at which point the string will be inserted into theinvoking StringBuffer object.

● Question : Write a program to insert "like" between "I" and "Java".

Page 39: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

h) reverse( ) : reverse the characters within a StringBuffer object.

StringBuffer reverse( )● Eg :

StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s);

I) delete( ) and deleteCharAt( ) : delete characters within a StringBuffer. StringBuffer delete(int startIndex int endIndex) //the substring deleted runs from startIndex to endIndex–1 StringBuffer deleteCharAt(int loc) //deletes the character at the index specified by loc

Page 40: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

j) replace( ) : replace one set of characters with another set inside a StringBuffer object.

StringBuffer replace(int startIndex, int endIndex, String str)● Substring being replaced is specified by the indexes startIndex and

endIndex. substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

● Eg: // 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); }}o/p- After replace: This was a test.

Page 41: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

k) substring( ) : You can obtain a portion of a StringBuffer by calling substring( ).String substring(int startIndex) //substring that starts at startIndex and runs to the endString substring(int startIndex, int endIndex) //substring that starts at startIndex and runs through endIndex–1.

Additional methods by StringBuffer :● StringBuffer appendCodePoint(int ch)● int codePointAt(int I)● int codePointBefore(int i)● int codePointCount(int start, int end)● int indexOf(String str)● int indexOf(String str, int startIndex)● int lastIndexOf(String str)● int lastIndexOf(String str, int startIndex)● int offsetByCodePoints(int start, int num)● CharSequence subSequence(int startIndex, int stopIndex)● void trimToSize( )

Page 42: Unit 4 Java as OOP Language String Handling · 2017-02-28 · About String in JAVA • Java implements strings as objects of type String. • String objects can be constructed a number

StringBuilder

● Introduced by JDK 5, StringBuilder is a relatively recent addition to Java’sstring handling capabilities.

● StringBuilder is similar to StringBuffer except one difference, it is not synchronized,i.e. it is not thread-safe.

● advantage of StringBuilderis faster performance.