Menu
Topics Index
...
`


Strings > StringBuffer >
Siva Nookala - 05 Apr 2016
This method replaces the characters in a substring of this sequence with characters in the specified String.

The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start.

StringBuffer Method:
MethodDescription
StringBuffer replace(int start, int end, String str)Replaces the characters in a substring of this sequence with characters in the specified String.

StringBufferDemo6
class StringBufferDemo6
{
    public static void main(String[] args) {
    
        StringBuffer buff = new StringBuffer("Java Util Package"); // LINE A
        System.out.println("Stringbuffer = " + buff);
    
        // replace substring from index 5 to index 9
        buff.replace(5, 9, "Lang"); // LINE B
    
        // prints the stringbuffer after replacing
        System.out.println("After replacing: " + buff);
    }

}
OUTPUT

Stringbuffer = Java Util Package
After replacing: Java Lang Package

DESCRIPTION

In the above program at LINE A we have created a StringBuffer object with String "Java Util Package" and printed it. At LINE B we have replaced the substring starting at index 5 and ending at index 9 with "Lang" and printed.

THINGS TO TRY
  • Replace LINE B in the above program with the code below.
    buff.replace(0, buff.length(), "Merit Campus");
    Output after replacing will be: Merit Campus.
  • Replace LINE B in the above program with the code below.
    buff.replace(4, 17, ".meritcampus.com");
    Output after replacing will be: Java.meritcampus.com. Here we are replacing the substring starting from index 4 and ending at 17 in the StringBuffer with the ".meritcampus.com"

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App