Showing posts with label StringBuffer. Show all posts
Showing posts with label StringBuffer. Show all posts

StringBuffer in Java

The StringBuffer class is similar to String class and something more. The string class creates fixed length  while StringBuffer can create flexible length that can be altered in terms of length and content and also provides ability to modify the actual string.

Let us look at the following example which uses the StringBuffer class to replace the content of StringBuffer object from “Hello word” to “Hello java”.

public class sample
{
            public static void main(String args[])
                        {
                                    StringBuffer sb = new StringBuffer(“Hello word”);
                                    sb.replace(6,10,”java”);
                                    System.out.println(sb);
                        }
}

Output
Hello java

StringBuffer class methods

The following table demonstrates list of methods that can be used for string manipulation.



Method
Meaning
1
StringBuffer append(String st)
Appends the string to the string buffer.
2
StringBuffer delete(int start, int end)
Removes substring starting from start up to end of the string buffer.
3
StringBuffer insert(int pos, String st)
Insert the String into the string buffer
4
StringBuffer replace(int start, int end, String st)
Replace substring starting from start up to end of the string buffer.
5
StringBuffer reverse()
Returns reverse sequence of character of string buffer

Java Programming Example to check whether the given string is palindrome or not?

This program will accept string from the user through keyboard and display whether the given string is palindrome or not.

import java.io.*;

/**
 *
 * @author JavaHotSpot
 */

public class palindrome
{
  public static void main(String args[])
 {
     String s1,s2;
     int length;
     DataInputStream d;
     try
     {
     System.out.println("Enter the String");
     d=new DataInputStream(System.in);
     s1=(String)d.readLine();
     StringBuffer sb;
     sb=new StringBuffer(s1);
     s2=sb.reverse().toString();
     System.out.println("The Reverse of the string is "+s2);
     if(s1.equals(s2))
     {
         System.out.println("The given string is palindrome");
     }
     else
     {
         System.out.println("The given string is not palindrome");
     }
     }
     catch(Exception e)
     {
         System.out.println(e.toString());
     }
 }
}

Output:

Run 1:
Enter the String
Javaatweet
The Reverse of the string is teewaavaJ
The given string is not palindrome

Run 2:
Enter the String
madam
The Reverse of the string is madam
The given string is palindrome