Key differences between String and StringBuffer Class in Java

String Class in Java

In Java, the String class is a fundamental data type used to represent sequences of characters and provides a wide array of methods to manipulate these sequences. Strings in Java are immutable, meaning once a String object is created, its value cannot be changed. This design choice enhances performance by allowing multiple references to the same String object without the need for copying the underlying value for safety. Instead of modifying an existing string, any operation that appears to alter it actually results in the creation of a new String object. The String class is part of the java.lang package, which is automatically imported into all Java programs. String objects can be created directly by enclosing characters in double quotes or through constructors provided by the String class.

Functions of String Class in Java:

  1. length():

Returns the number of characters in the string, which is useful for looping through or validating the length of the string.

  1. charAt():

Retrieves the character at a specified index within the string, allowing individual characters to be read.

  1. substring():

Extracts a portion of the string from a beginning index to an optional ending index, creating a new string from the specified segment.

  1. contains():

Checks if the string contains a specified sequence of characters, which is useful for searching within strings.

  1. equals():

Compares two strings for content equality, checking if they contain exactly the same characters in the same order.

  1. startsWith():

Determines if the string begins with the specified prefix, which can be used for filtering or matching strings.

  1. endsWith():

Checks whether the string ends with the specified suffix, useful for sorting or classifying strings based on their endings.

  1. replace():

Creates a new string by replacing all occurrences of a specified character or substring with another character or substring, which is essential for string manipulation tasks like cleaning or modifying content.

Example of String Class in Java:

Here’s an example demonstrating the use of the String class in Java, which incorporates several methods to manipulate and process string data:

public class StringExample {

    public static void main(String[] args) {

        // Creating strings using the String class

        String greeting = “Hello, World!”;

        String name = “Java”;

        // Using String methods

        System.out.println(“Length of greeting: ” + greeting.length()); // Length of the string

        System.out.println(“Character at position 7: ” + greeting.charAt(6)); // Retrieves character at index 6

        System.out.println(“Substring from greeting: ” + greeting.substring(7)); // Extracts substring from index 7 to the end

        System.out.println(“Does greeting contain ‘World’? ” + greeting.contains(“World”)); // Checks if “World” is in greeting

        System.out.println(“Greeting equals ‘hello, world!’? ” + greeting.equalsIgnoreCase(“hello, world!”)); // Case-insensitive comparison

        System.out.println(“Greeting starts with ‘Hello’? ” + greeting.startsWith(“Hello”)); // Checks if it starts with “Hello”

        System.out.println(“Greeting ends with ‘World!’? ” + greeting.endsWith(“World!”)); // Checks if it ends with “World!”

        System.out.println(“Replace ‘World’ with ‘Java’: ” + greeting.replace(“World”, “Java”)); // Replaces “World” with “Java”

        // Concatenation example

        String completeGreeting = greeting.substring(0, 5) + ” ” + name + “!”;

        System.out.println(“Custom greeting: ” + completeGreeting); // Outputs: Hello Java!

    }

}

This program illustrates how to create strings and use various methods of the String class, such as length(), charAt(), substring(), contains(), equalsIgnoreCase(), startsWith(), endsWith(), and replace(). These methods are commonly used for processing text, such as modifying content, checking the presence of substrings, or comparing strings. The concatenation at the end of the example demonstrates combining strings effectively to form new string values. 

StringBuffer Class in Java

The StringBuffer class in Java provides a way to create and manipulate strings that are mutable, unlike the immutable String class. This means that instances of StringBuffer can be modified after they are created through methods like append, insert, reverse, and delete, which are not available in the immutable String class. StringBuffer is synchronized, making it thread-safe, which means multiple threads can modify a StringBuffer object without causing data inconsistencies. This class is especially useful when you have to make numerous modifications to a string of characters in a multi-threaded environment. StringBuffer is part of the java.lang package and is commonly used when there is a necessity to frequently change the contents of a string during the execution of a program.

Functions of StringBuffer Class in Java:

  • String Modification:

Allows modification of characters within the string without creating a new object each time.

  • Append Function:

Provides methods like append() to add text at the end of the existing buffer.

  • Insert Function:

Allows insertion of text at any given point within the string using insert().

  • Delete Function:

Facilitates removal of characters from the buffer using methods like delete() and deleteCharAt().

  • Reverse Function:

Can reverse the character sequence using the reverse() method, which is useful for algorithms that require such operations.

  • Capacity Management:

Automatically increases the capacity if the appended or inserted data exceeds the current capacity.

  • Length Adjustment:

Allows adjustment of the length of the string using setLength(), making it flexible for varying string manipulation needs.

  • Thread Safety:

It is thread-safe, meaning it can be used in a multithreaded environment without additional synchronization.

Example of StringBuffer Class in Java:

This example showcases several operations such as appending, inserting, reversing, and deleting within a StringBuffer.

public class StringBufferExample {

    public static void main(String[] args) {

        // Create a new StringBuffer instance

        StringBuffer sb = new StringBuffer(“Hello”);

        // Append ” World” to the StringBuffer

        sb.append(” World”);

        System.out.println(“After append: ” + sb);

        // Insert a comma after “Hello”

        sb.insert(5, “,”);

        System.out.println(“After insert: ” + sb);

        // Reverse the StringBuffer

        sb.reverse();

        System.out.println(“After reverse: ” + sb);

        // Delete the characters from index 0 to 5

        sb.delete(0, 5);

        System.out.println(“After delete: ” + sb);

        // Set the length of the StringBuffer

        sb.setLength(3);

        System.out.println(“After setting length: ” + sb);

    }

}

Explanation:

  • Initialization: A StringBuffer object sb is created with the content “Hello”.
  • Append: ” World” is appended to sb, resulting in “Hello World”.
  • Insert: A comma is inserted right after “Hello”, making it “Hello, World”.
  • Reverse: The entire content of sb is reversed to become “dlroW ,olleH”.
  • Delete: The first five characters (“dlroW”) are removed, leaving “,olleH”.
  • Set Length: The length of sb is set to 3, trimming it down to “,ol”.

Key differences between String and StringBuffer Class in Java

Aspect String StringBuffer
Mutability Immutable Mutable
Performance Faster on constant Slower but thread-safe
Synchronization Not synchronized Synchronized
Storage Area Constant String Pool Heap
Memory Efficiency Less efficient if altered More efficient if altered
Thread Safety Thread-safe Thread-safe
Append Method Not available Available
Initial Capacity N/A 16 characters by default
Length and Capacity Fixed length Length vs. capacity
Reverse Function Not available Available
Insert Method Not available Available
Delete Method Not available Available
Modify in Place Not possible Possible
Recommended Use When constant When changing frequently
Constructor Variants Fewer options More options

Key Similarities between String and StringBuffer Class in Java

  • Text Storage:

Both are used to store and manipulate text data, effectively serving as sequences of characters.

  • Character Access:

Both classes allow accessing characters within the strings via indexed positions.

  • String Methods:

They share many common methods for string manipulation, such as length(), charAt(), and substring(), which function similarly in both classes.

  • Implementation of CharSequence Interface:

Both String and StringBuffer implement the CharSequence interface, which means they can be used in contexts where a sequence of characters is needed, such as in regex operations.

  • Support for Concatenation:

Although StringBuffer is designed for frequent modifications, both classes support adding additional text through methods or operators (+ for String and append() for StringBuffer).

  • Conversion to String:

StringBuffer can be easily converted to a String using its toString() method, indicating a close functional relationship in terms of output and usage.

  • Java API:

Both are integral parts of the Java API and are found in java.lang package, making them readily accessible without the need for importing additional libraries.

  • Used in Text Manipulation:

In practice, both are widely used in applications involving text processing and manipulation, albeit in different contexts based on their performance and mutability characteristics.

Leave a Reply

error: Content is protected !!