Copy/paste this code into a file StringBufferTest.java:

import java.awt.*;

// the program demonstrates various methods 
// of StringBuffer
public class StringBufferTest {

    public static void main (String [] args) {
	// create a new StringBuffer
        StringBuffer sillypoem1 = new StringBuffer();
	System.out.println(sillypoem1); // the StringBuffer is empty 
	// appending to an empty string
	sillypoem1.append("little monkeys jumping on the bed"); 

	// you can insert a number...
	int n = 5;
	sillypoem1.insert(0,n);
	System.out.println(sillypoem1);

	// ...or a string
	sillypoem1.insert(1, " ");
	System.out.println(sillypoem1);
	
	// create another StringBuffer, this time start with some text:
	StringBuffer sillypoem2 = new StringBuffer("!daeh sih tih dna");
	// more StringBuffer methods
	sillypoem2.reverse();
	System.out.println(sillypoem2);
	sillypoem2.insert(0,"One fell off ");
	System.out.println(sillypoem2);
	sillypoem2.replace(17,20,"bumped");
	System.out.println(sillypoem2);

	// replacing ! by :-(
	// find out the index of !
	int index = sillypoem2.indexOf("!");
	sillypoem2.replace(index, index +1, " :-(");
	System.out.println(sillypoem2);
	
	// creating a StringBuffer for the entire poem:
	StringBuffer wholething = new StringBuffer();
	wholething.append(sillypoem1);
	// appending a new line character after the first line:
	wholething.append('\n');
	// adding the second line:
	wholething.append(sillypoem2);
	
	// printing the result:
	System.out.println("\n\n**** Here is our wonderful poem: ****\n");
	System.out.println(wholething);
	System.out.println("\n**** The end ****\n");

	// Changing the first StringBuffer:
	sillypoem1.delete(0,1);
	System.out.println(sillypoem1);
	sillypoem1.insert(0,4);
	System.out.println(sillypoem1);

	// printing out wholething to see if it changed:
	System.out.println("\n\n**** Here is our wonderful poem: ****\n");
	System.out.println(wholething);
	System.out.println("\n**** The end ****\n");
    }

}

This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.