beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

StringBuffer Replace method Example

By Chaitanya Singh | Filed Under: StringBuffer

class StringBufferReplace{ 
  public static void main(String[] args) {
 
     //Create StringBuffer object
     StringBuffer sb = new StringBuffer("This is a String");
     System.out.println("Before: " + sb);
 
     /* public StringBuffer replace(int start, int end, String str):
      * It replaces the part of the content (substring starting from
      * index start and ending with index end-1) of StringBuffer with 
      * the specified string "str" 
      */
     sb.replace(10,16,"TEXT");
     System.out.println("After: " + sb);
  }
}

Output:

Before: This is a String
After: This is a TEXT

More about replace() method from javadoc:
public StringBuffer replace(int start, int end, String str): Replaces the substring of original string with the specified String. The substring begins at the specified index start and ends at index end – 1. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)

Parameters:
start – The beginning index, inclusive.
end – The ending index, exclusive.
str – String that will replace previous contents.

It throws:
StringIndexOutOfBoundsException – if start index is negative, greater than length(), or greater than specified index end.

Enjoyed this post? Try these related posts

  1. StringBuffer substring method Example
  2. Difference between String and StringBuffer
  3. Java – How null works with StringBuffer
  4. Difference between StringBuilder and StringBuffer
  5. Java – How to append a newline to StringBuffer

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap