indexOf() StringBuffer Example

December 14, 2014 | class StringBuffer

java.lang.StringBuffer class comes with many helper methods to manipulate string. One of the methods is overloaded indexOf() method used to search for the first occurrence of a string in the buffer.


Let us see what Java API says about indexOf() StringBuffer:

  • public int indexOf(String searchString): Returns an int value of the index number of first occurrence of searchString in the buffer. Returns -1 if the searchString is not found.
  • public synchronized int indexOf(String searchString, int searchIndex): Returns an int value of the index number of first occurrence of searchString in the buffer where search starts from searchIndex. Returns -1 if the searchString is not found.
Following indexOf() StringBuffer example illustrates the usage of two overloaded method in all possible ways.
public class Demo
{
  public static void main(String args[])
  {				            // hello comes in 3 places	
   StringBuffer sb1 = new StringBuffer("123hello456hello789hello");    
                                            // to find 1st occurrence of hello
   int x = sb1.indexOf("hello");   
   System.out.println("First Occurrence of hello: " + x);

                                            // to find first occurrence of hello starting from 9th index number
   x = sb1.indexOf("hello", 9);   
   System.out.println("Occurrence of hello from index 9: " + x);

   x = sb1.indexOf("world");   	            // world does not exist
   System.out.println("Occurrence of world which does not exist: " + x);
 }
}

indexOf() StringBuffer Output screenshot on indexOf() StringBuffer example

Pass your comments and suggestions on this tutorial "indexOf() StringBuffer Example".