Home‎ > ‎Applied Core Java‎ > ‎Introduction‎ > ‎

Test StringBuffer Class

Problem : Describe java.lang.StringBuffer class methods

Program :

Step 1 - Coding

Create a text file c:\sunilos\TestStringBuffer.java  and copy below contents.

/*

 * A program implements String Buffer.
*/

public class TestStringBuffer {

    public static void main(String[] args) {
       
        StringBuffer sb = new StringBuffer("Vijay");  // Buffer is intialized by string "Vijay"

        sb.append(" Dinanath"); // Now append string " Dinanath" in string buffer

        sb.append(" Chouhan"); // Now append string " Chouhan" in string buffer

        String name = sb.toString(); // Convert StringBuffer into String object;

        System.out.println(" Buffer Length- " + sb.length()); // Find length of buffer
                                                               
        System.out.println(" Buffer Capacity- " + sb.capacity()); // Find capacity of buffer
   
        System.out.println(" Character at position 6 - " + sb.charAt(6));// Find charAt given position
       
        System.out.println(" Dina index is- " + sb.indexOf("Dina")); // Find index of buffer   
       
        System.out.println(" Last i Position- " + sb.lastIndexOf("i")); // Find last i index of buffer
       
        System.out.println(" subString is- " + sb.substring(13)); // Find subString of buffer

        System.out.println(" subString is start at 6 and ends at 13- " + sb.substring(6, 13));
       
        System.out.println(" reverse the string - " + sb.reverse()); // reverse the string of buffer
       
        System.out.println(" 6 to 13 position is replaced by aaaaa- " + sb.replace(6, 13, "aaaaa"));
       
        System.out.println(" Delete at position at 6 to 12 is- " + sb.delete(6, 12));
       
        System.out.println(" Delete char at 8 postion is - " + sb.deleteCharAt(8));
       
    }
}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestStringBuffer.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestStringBuffer.java with help of 
    • javac TestStringBuffer.java command. Command will create class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestStringBuffer command.

Output

 Buffer Length- 20
 Buffer Capacity- 21
 Character at position 6 - D
 Dina index is- 6
 Last i Position- 7
 subString is-  Chohan
 subString is start at 6 and ends at 13- Dinanth
 reverse the string - nahohC htnaniD yajiV
 6 to 13 position is replaced by aaaaa- nahohCaaaaaD yajiV
 Delete at position at 6 to 12 is- nahohC yajiV
 Delete char at 8 postion is - nahohC yjiV



<<Previous | Next>>
ċ
TestStringBuffer.java
(2k)
Mahima Hardia,
Aug 19, 2011, 2:56 AM
Comments