Immutable String

What are Immutable objects?

The objects which once declared elements can’t be modified or changed are called immutable objects. Common examples of immutable classes in Java include String, Integer, Double, Character, LocalDate, and more.

Is String Immutable?

Yes, In Java, a string is immutable, which means once it is created, its content cannot be changed. When you perform operations that appear to modify a string, you are actually creating a new string with the modified content. The original string remains unchanged in memory. The immutability of strings in Java has several implications:

No Modification: You cannot change the characters of a string once it is created. Any attempt to modify a string results in the creation of a new string object.

Thread Safety: Since strings cannot be changed, they are inherently thread-safe. Multiple threads can safely share and access the same string without worrying about concurrent modifications.

Caching: Due to immutability, Java can cache string literals, which improves performance and memory usage. When you use the same string literal in multiple places in your code, Java reuses the same string object from the string pool.

The immutability of strings ensures their stability and integrity, making them reliable for various purposes, including as keys in data structures, as constants in the code, and when dealing with multithreaded environments.

Example:
public class StringImmutability {
    public static void main(String[] args) {
        String s = "Hello";
        String r = s.concat(" Java!");

        System.out.println("Original String: " + s);
        System.out.println("Modified String: " + r);
    }
}
Output:

Original String: Hello

Modified String: Hello Java

In this example, we use the concat() method to add “Java!” to the original string “Hello.” However, the original string remains unchanged, and a new string object is created with the modified content.

Why String class is Final in Java?

In Java, the String class is marked as final, which means it cannot be subclassed or extended by other classes.The String class is final to prevent the overriding of its methods, ensuring that both old and new String objects have access to the same features. Making the String class final is a design choice that ensures the security, immutability, and consistency of strings in Java and contributes to the overall robustness of the language.

StringBuilder  &  StringBuffer:

It’s important to note that while the String class is final, Java provides other classes like StringBuilder and StringBuffer for more efficient string manipulation, especially when you need to perform multiple modifications on a string. These classes are mutable and can be used when you need to build or modify strings dynamically.

StringBuilder:

‘StringBuilder` is a class in Java that represents a mutable sequence of characters. Once a `String` object is created, it cannot be altered. However, using `StringBuilder` allows for modifications to the content of the string without creating new objects. This makes `StringBuilder` more efficient when you need to perform multiple modifications or concatenations on a string.

The `StringBuilder` class is part of the `java.lang` package and provides various methods to manipulate strings efficiently. Some of the important characteristics and methods of the `StringBuilder` class include:

  1. Mutability: As mentioned earlier, `StringBuilder` is mutable, which means you can modify the contents of the string it holds.
  2. Efficiency: Because `StringBuilder` is mutable, it avoids the overhead of creating new string objects for each modification, making it more memory-efficient and faster for building and modifying strings.
  3. Methods for Concatenation: The `StringBuilder` class provides the `append()` method, which allows you to concatenate different data types to the string, such as characters, strings, numbers, and objects.
  4. Chaining: The `append()` method returns the `StringBuilder` instance itself, allowing you to chain multiple `append()` calls together for concise and readable code.
  5. Capacity Management: `StringBuilder` has an initial capacity, which can be specified during its creation. It also automatically increases its capacity as needed to accommodate larger strings.

Constructors of StringBuilder:

Constructor                                    Description
StringBuilder()  It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str)  It creates a String Builder with the specified string.
StringBuilder(int length)  It creates an empty String Builder with the specified capacity as length.
Example:

Here’s a simple example of using StringBuilder:

public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();

        sb.append("Hello");
        sb.append(", ");
        sb.append("World!");

        String result = sb.toString();
        System.out.println(result); // Output: "Hello, World!"
    }
}
Output:

Hello, World!

Explanation:

Let’s explain the code:

  • public class StringBuilderExample {: This line defines the beginning of a class named StringBuilderExample.
  • public static void main(String[] args) {: This is the main method, which serves as the entry point for the program.
  • StringBuilder sb = new StringBuilder();: Here, a new StringBuilder object named sb is created. The StringBuilder class provides a more efficient way to manipulate strings when you need to perform multiple concatenations or modifications.
  • sb.append(“Hello”);: The append() method of the StringBuilder class is used to add the string “Hello” to the sb object. This method adds the provided string to the end of the current content of the StringBuilder.
  • sb.append(“, “);: This line appends the string “, ” (a comma followed by a space) to the existing content in the sb object.
  • sb.append(“World!”);: Similarly, this line adds the string “World!” to the StringBuilder.
  • String result = sb.toString();: The toString() method of the StringBuilder class is called to convert the content of the sb object into a regular String object named result. This step is necessary if you want to use the final concatenated string as a regular string.
  • System.out.println(result);: Finally, the concatenated string stored in the result variable is printed to the console using the System.out.println() method. The output will be: “Hello, World!”

In summary, the code uses a StringBuilder object to efficiently build a string by appending multiple smaller strings together. This is more memory-efficient than using multiple string concatenations with the + operator, especially when working with a large number of concatenations. The result is “Hello, World!”, which is printed on the console.

Keep in mind that when you have multiple string concatenations or modifications within a loop, using StringBuilder is generally preferred over repeatedly using the + operator or concat() method, as it reduces unnecessary object creations and improves performance.

String Buffer:

In Java, the `StringBuffer` class is part of the `java.lang` package and provides a mutable sequence of characters. It is used to efficiently construct and manipulate strings without creating multiple intermediate string objects, which can be particularly useful when dealing with large strings or performing frequent string modifications.

These are important facts to know about the `StringBuffer` class:

  1. Mutability: Unlike the regular `String` class in Java, which is immutable (i.e., once created, its value cannot be changed), `StringBuffer` is mutable. You can modify its content after creating the object.
  2. Character sequence: Internally, a `StringBuffer` uses a character array to store its content. It can dynamically resize the array as needed to accommodate the growing string.
  3. Thread-safe: The `StringBuffer` class is synchronized, which means it is thread-safe. This makes it safe to use in multi-threaded environments where multiple threads might be modifying the same `StringBuffer` instance simultaneously. However, its synchronized nature can introduce some performance overhead.
  4. Performance: While `StringBuffer` provides a convenient way to manipulate strings efficiently, it can be less performant than the non-synchronized variant `StringBuilder`. If you are working in a single-threaded environment, consider using `StringBuilder` instead, which is a non-synchronized version of `StringBuffer` and generally faster.

Constructors of StringBuffer:

Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
Example:
public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer stringBuffer = new StringBuffer();

        // Appending content to the StringBuffer
        stringBuffer.append("Hello");
        stringBuffer.append(" ");
        stringBuffer.append("Java");
        stringBuffer.append("!");

        System.out.println("Resulting string: " + stringBuffer.toString());

        // Modifying content
        stringBuffer.insert(5, " my");
        stringBuffer.replace(6, 10, "dear");
        stringBuffer.delete(11, 15);

        System.out.println("Modified string: " + stringBuffer.toString());
    }
}
Output:

Resulting string: Hello Java!

Modified string: Hello dear

Explanation:

In this example:

  1. We create a StringBuffer instance named stringBuffer.
  2. We append three different substrings (“Hello”, ” “, “Java”, and “!”) to the stringBuffer.
  3. The first output displays the resulting string after appending, which is “Hello Java!”.
  4. We then demonstrate string modification using various methods:
  5. insert(5, ” my”): Inserts ” my” at the 5th index of the stringBuffer, resulting in “Hello my Java!”.
  6. replace(6, 10, “dear”): Replaces the characters from the 6th to 9th index (exclusive) with “dear”, giving us “Hello dear Java!”.
  7. delete(11, 15): Deletes the characters from the 11th to 14th index (exclusive), leading to “Hello dear!”.
  8. The second output displays the modified string, which is “Hello dear!”.


(adsbygoogle = window.adsbygoogle || []).push({});


(adsbygoogle = window.adsbygoogle || []).push({});

Visited 1 times, 1 visit(s) today

Comments are closed.

Close