Program to show use of some 'StringBuffer' class methods

StringBuffer class is like a String, but can be modified. StringBuffer class is mutable. StringBuffer is fast and consumes less memory when you concat strings. For example,
// Constructs string buffer with no characters in it 
// and an initial capacity of 16 characters.
StringBuffer  s1 = new StringBuffer( );    
OR

// Constructs a string buffer with no characters in it and the specified 
// initial capacity to 5.
StringBuffer  s2 = new StringBuffer(5);

// Constructs a string buffer that contains the three characters.  
// The initial capacity of the string buffer is 16 plus 
// the length of the "abc" string in short it is 19. 
StringBuffer s3 = new StringBuffer("abc");

We have used the following methods of StringBuffer class:
  • capacity( ) : It returns the current capacity.
  • lastIndexOf(String str) : It returns the index within this string of the rightmost occurrence of the specified substring.
  • reverse( ) : It causes the character sequence to be replaced by the reverse of the sequence.


PROGRAM
class UsingStringBufferMethods {

 public static void main(String[] args) {
  
  StringBuffer s = new StringBuffer(5);
  System.out.println("String capacity : "+s.capacity());
  s = new StringBuffer("Hello Java");
  System.out.println("String Given : "+s);
  System.out.println("Last index of 'Java' is : " + s.lastIndexOf("Java"));
  StringBuffer strRev = s.reverse();
  System.out.println("Now String is : "+s);
  System.out.println("Reverse String : "+strRev);
 }
}
OUTPUT
C:\>javac UsingStringBufferMethods.java
C:\>java UsingStringBufferMethods
String capacity : 5
String Given : Hello Java
Last index of 'Java' is : 6
Now String is : avaJ olleH
Reverse String : avaJ olleH

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative