Skip to content

vyasdeepti/StringBuffer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

StringBuffer Operations

A comprehensive Java project demonstrating various operations and methods of the StringBuffer class. This repository contains practical examples for learning how to manipulate mutable strings in Java.

📚 Overview

StringBuffer is a thread-safe, mutable sequence of characters in Java. Unlike String, which is immutable, StringBuffer allows you to modify the content of the string. This project showcases the most common and useful operations provided by the StringBuffer class.

Key Features:

  • Thread-safe string manipulation
  • Mutable character sequences
  • Efficient string concatenation and modification
  • Dynamic capacity management

🎯 Project Structure

StringBuffer/
├── Stringbuffer/
│   ├── src/
│   │   ├── StringbufferAppend.java      # append() method demonstration
│   │   ├── StringbufferCapacity.java    # capacity() method demonstration
│   │   ├── StringbufferDelete.java      # delete() method demonstration
│   │   ├── StringbufferInsert.java      # insert() method demonstration
│   │   ├── StringbufferReplace.java     # replace() method demonstration
│   │   └── StringbufferReverse.java     # reverse() method demonstration
│   └── .classpath                       # Eclipse project configuration
└── README.md                             # This file

📋 StringBuffer Methods Covered

1. append() - Add text at the end

Appends the specified string to the existing content.

File: StringbufferAppend.java

class StringbufferAppend{  
    public static void main(String args[]){  
        StringBuffer sb = new StringBuffer("Hello ");  
        sb.append("Java"); // Append "Java" to the end
        System.out.println(sb);
    }  
}

Output:

Hello Java

Explanation: The append() method concatenates "Java" to the existing "Hello ", resulting in "Hello Java".


2. capacity() - Get and understand buffer capacity

Returns the current capacity of the StringBuffer. The default capacity is 16.

File: StringbufferCapacity.java

public class StringbufferCapacity {
    public static void main(String args[]){  
        StringBuffer sb = new StringBuffer();  
        System.out.println(sb.capacity()); // Default capacity
        
        sb.append("Hello");  
        System.out.println(sb.capacity()); // Still 16
        
        sb.append("Java is my Favourite Subject");  
        System.out.println(sb.capacity()); // Expanded capacity
    }  
}

Output:

16
16
34

Explanation:

  • Initial capacity: 16 (default)
  • After appending "Hello" (5 chars): still 16 (enough space)
  • After appending longer text: capacity expands to (16 × 2) + 2 = 34

3. delete() - Remove characters from a range

Removes characters from the specified range (startIndex to endIndex, where endIndex is exclusive).

File: StringbufferDelete.java

public class StringbufferDelete {
    public static void main(String args[]){  
        StringBuffer sb = new StringBuffer("University");  
        sb.delete(1, 3); // Remove characters at index 1-2
        System.out.println(sb);
        
        StringBuffer sb1 = new StringBuffer("University"); 
        sb1.delete(4, 7); // Remove characters at index 4-6
        System.out.println(sb1);
        
        StringBuffer sb2 = new StringBuffer("University"); 
        sb2.delete(3, 5); // Remove characters at index 3-4
        System.out.println(sb2);
    }  
}

Output:

Uiversity
Univty
Uniaersity

Explanation:

  • Original: "University" (U=0, n=1, i=2, v=3, e=4, r=5, s=6, i=7, t=8, y=9)
  • delete(1, 3): Removes 'n' and 'i' → "Uiversity"
  • delete(4, 7): Removes 'e', 'r', 's' → "Univty"
  • delete(3, 5): Removes 'v' and 'e' → "Uniaersity"

4. insert() - Insert text at specific position

Inserts the specified string at the given index.

File: StringbufferInsert.java

public class StringbufferInsert {
    public static void main(String args[]){  
        StringBuffer sb = new StringBuffer("Hello ");  
        sb.insert(1, "Java"); // Insert "Java" at index 1
        System.out.println(sb);
    }  
}

Output:

HJavaello

Explanation: Inserts "Java" after the first character 'H' (at index 1), resulting in "HJavaello".


5. replace() - Replace characters in a range

Replaces the characters in a substring with the specified string.

File: StringbufferReplace.java

public class StringbufferReplace {
    public static void main(String args[]){  
        StringBuffer sb = new StringBuffer("University");  
        sb.replace(1, 6, "Java"); // Replace index 1-5 with "Java"
        System.out.println(sb);
    }  
}

Output:

UJavaity

Explanation: Replaces characters from index 1 to 5 ("niver") with "Java", resulting in "UJavaity".


6. reverse() - Reverse the string

Reverses the character sequence.

File: StringbufferReverse.java

public class StringbufferReverse {
    public static void main(String args[]){  
        StringBuffer sb = new StringBuffer("Saturday Sunday");  
        sb.reverse();  
        System.out.println(sb);
        
        StringBuffer sb1 = new StringBuffer("Assignment");  
        sb1.reverse();  
        System.out.println(sb1);
        
        StringBuffer sb2 = new StringBuffer("Hello! I am John.");  
        sb2.reverse();  
        System.out.println(sb2);
    }  
}

Output:

yadnuS yrutaS
tnemngissA
.nhoJ ma I !olleH

Explanation: The reverse() method reverses the entire sequence of characters, including spaces and special characters.


🚀 How to Run

Using Eclipse IDE:

  1. Open Eclipse
  2. File → Import → General → Existing Projects into Workspace
  3. Select the repository folder
  4. Right-click on any .java file
  5. Run As → Java Application

Using Command Line:

cd Stringbuffer/src

# Compile all files
javac *.java

# Run individual programs
java StringbufferAppend
java StringbufferCapacity
java StringbufferDelete
java StringbufferInsert
java StringbufferReplace
java StringbufferReverse

📊 Comparison: String vs StringBuffer

Feature String StringBuffer
Mutability Immutable Mutable
Thread-Safe Yes (immutable) Yes (synchronized)
Performance Slower for modifications Faster for modifications
Memory Creates new object each time Modifies existing object
Use Case Read-only operations Frequent modifications

💡 Key Concepts

1. Mutability

StringBuffer allows modification of the string content without creating new objects, making it memory-efficient for string manipulation.

2. Capacity vs Length

  • Length: Number of actual characters in the StringBuffer
  • Capacity: Size of the buffer that can hold characters before resizing

3. Thread Safety

StringBuffer methods are synchronized, making it safe for use in multi-threaded environments. For single-threaded operations, consider using StringBuilder for better performance.

4. Index-based Operations

Most operations use 0-based indexing:

  • Index 0 = First character
  • Index n-1 = Last character
  • Range operations are typically startIndex (inclusive) to endIndex (exclusive)

📝 Common Use Cases

  • Iterative String Building: Efficiently build strings in loops
  • String Manipulation: Modify, insert, replace, or reverse strings
  • Thread-Safe Operations: Use in multi-threaded applications
  • Dynamic Content: Build strings where content changes frequently

🔗 Related Classes

  • String: Immutable string class
  • StringBuilder: Non-synchronized mutable string class (preferred for single-threaded applications)

📚 Learning Resources

This project is ideal for:

  • Java beginners learning string manipulation
  • Understanding the difference between String and StringBuffer
  • Practicing object-oriented programming
  • Preparing for Java interviews

⚠️ Performance Notes

  • StringBuffer is thread-safe but has synchronization overhead
  • For single-threaded code, use StringBuilder instead (faster)
  • Use StringBuffer.append() in loops instead of String concatenation with +

🤝 Contributing

Feel free to fork this repository and add more examples or improvements!

📄 License

This project is open source and available under the MIT License.


Happy Learning! 🎓

For more information about StringBuffer, visit the Java Documentation.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages