• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Array » StringBuffer Class in Java Example
Next →
← Prev

StringBuffer Class in Java Example

By Dinesh Thakur

StringBuffer represents grow able and write able character sequences. We can modify the StringBuffer object, i.e. we can append more characters or may insert a substring in middle. StringBuffer will automatically grow to make room for such additions and is very flexible to the modifications.

StringBuffer Constructors

 

StringBuffer defines these three constructors:

StringBuffer()

It reserves room for 16 characters without reallocation.

StringBuffer(int size)

It accepts an integer argument that explicitly sets the size of the buffer.

StringBuffer(String str)

It accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.

length( ) and capacity( )

The current length of a StringBuffer can be found by the length() method, while the total allocated capacity can be found through the capacity() method.

Syntax:

int length()

int capacity()

ensureCapacity( )

If we want to preallocate room for a certain number of characters after a StringBuffer has been constructed, we can use ensureCapacity() to set the size of the buffer.

Syntax:

void ensureCapacity(int capacity)

Here, capacity specifies the size of the buffer.

setLength()

It is used to set the length of the buffer within a StringBuffer object.

Syntax:

void setLength(int len)

Here, len specifies the length of the buffer. This value must be nonnegative. When we increase the size of the buffer, null characters are added to the end of the existing buffer. If we call setLength() with a value less than the current value returned by length(), then the characters stored beyond the new length will be lost.

charAt() and setCharAt( )

A single character can be obtained from a StringBuffer by the charAt() method. We can even set the value of a character within a StringBuffer using setCharAt().

Syntax:

char charAt(int loe}

void setCharAt(int loc, char ch)

loc specifies the location of the character being obtained. For setCharAt(), loc specifies the location of the character being set, and ch specifies the new value of that character. For both methods, loc must be nonnegative and must not specify a location beyond the end of the buffer.

getChars()

To copy a substring of a StringBuffer into an array, use the getChars() method.

Syntax:

void getChars(int si, int e, char t[ ], int ti)

Here, si specifies the index of the beginning of the substring, and e specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from si through e-l. The array that will receive the characters is specified by t. The index within t at which the substring will be copied is passed in ti.

append( )

The append() method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object..

Syntax:

StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obf)

String.valueOf() is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append().

The append() method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append() on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString() to turn the modifiable StringBuffer back into a constant String

import java.io.*;
public class ReversedString
{
            public static String reverseIt(String s)
            {
                        int i, n;
                        n = s.length();
                        StringBuffer d = new StringBuffer(n);
                        for (i = n - 1; i >= 0; i--)
                                    d.append(s.charAt(i));
                        return d.toString();
            }
            public static void main (String args[]) throws IOException
            {
                        BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
                        String p,q;
                        System.out.println("Enter a string");
                        p=k.readLine();
                        q=reverseIt(p);
                        System.out.println("Original String is "+p);
                        System.out.println("Reversed String is "+q);
            }
}

Insert()

The insert() method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append(), it calls String.valueOf () to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object.

Syntax:

StringBuffer insert(int loc, String str)

StringBuffer insert(int loc, char ch)

StringBuffer insert(int loc, Object obj)

Here, loc specifies the location at which point the string will be inserted into the invoking StringBuffer object.

public class StringInsert           
{
          public static void main(String args[])
            {
                        StringBuffer sb = new StringBuffer(" in ");
                        sb.append("God");
                        sb.append('!');
                        sb.insert(0,"Beleive");
                                sb.append('\n');
                        sb.append("God is Great");
                        sb.setCharAt(20,'I');
                        String s = sb.toString();
                        System.out.println(s);
            }
}

reverse()

 

We can reverse the characters within a StringBuffer object using reverse()·

import java.io.*;
class StringReverse
{
            public static void main(String args[])
            {
                        StringBuffer k=new StringBuffer("Hello Java");
                        System.out.println(k);
                        k.reverse();
                        System.out.println(k);
            }
}

delete( ) and deleteCharAt( )

StringBuffer delete(int s, int e)

StringBuffer deleteCharAt(int loc)

The delete() method deletes a sequence of characters from the invoking object. Here, s specifies the starting location of the first character to remove, and e specifies location one past the last character to remove. Thus, the substring deleted runs from s to e-l. The resulting StringBuffer object is returned.

The deleteCharAt() method deletes the character at the location specified by loco It returns the resulting StringBuffer object.

Replace()

It replaces one set of characters with another set inside a StringBuffer object.

Syntax:

StringBuffer replace(int s, int e, String str)

The substring being replaced is specified by the location sand e. Thus, the substring at s through e-l is replaced by str string.

substring( )

It returns a portion of a StringBuffer.

Syntax:

String substring(int s)

String substring(int s, int e)

The first form returns the substring that starts at s and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at s and runs through e-l.

public class StringBuffer2 
{
            public static void main (String args[])
            {
                        StringBuffer p= new StringBuffer("God is Great");
                        char k[] = new char[20];
                        char q;
                        p.getChars(7,11,k,0);
                        System.out.println("Original string is "+p);
                        p.delete(4,6);
                        System.out.println("string after deleting a word "+p);
                        p.insert(4,"is");
                        System.out.println("string after inserting a word "+p);
                        p.deleteCharAt(4);
                        System.out.println("string after deleting a character"+p);
                        p.replace(4,5,"always");
                        System.out.println("string after replacing a word is "+p);
                        q=p.charAt(0);
                        System.out.println("the first character of string is "+q);
            }
}

You’ll also like:

  1. StringBuffer setLength() in Java Example
  2. StringBuffer charAt() Java Example
  3. StringBuffer substring() Java Example
  4. StringBuffer setCharAt() Java Example
  5. StringBuffer deleteCharAt() Method in Java Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW