Problems with Strings

by | Dec 20, 2020 | Java

Introduction

Objects of the String class are immutable that is, once initialized, the string cannot be changed or modified. This happens because all the string objects are cached in the String pool. Two same strings create two reference points rather than adding it twice to the pool to save memory. Therefore, if a string object was to be mutable, the string in the pool would have to be changed thereby completing rendering useless the already created reference point. Also, as Strings are very popular as HashMap keys, if they are mutable, one would not be able to retrieve the original value object using a particular key.

However, the StringBuffer and the StringBuilder class objects are mutable. StringBuffer is threadsafe whereas StringBuilder is unsynchronized and not perfectly thread-safe. Although strings are still popularly used, the inclusion of StringBuilders and StringBuffers as a replacement is growing rapidly among developers. If you are working with a single-threaded program, StringBuilder is the fastest out of the three.

Example

Below is a simple program that illustrates the various ways in which you can add two or more strings using the String class, the StringBuilder class, as well as the StringBuffer class.

class SampleStrings
{
// String concatenation of two strings
public static void concat1(String s1)
{
s1 = s1 + " World";
}
// StringBuilder concatenation
public static void concat2(StringBuilder s2)
{
s2.append(" World");
}
// StringBuffer Concatenation
public static void concat3(StringBuffer s3)
{
s3.append(" World");
}
public static void main(String[] args)
{
String s1 = "Hello"; concat1(s1);  // s1 is not changes as it is immutable
System.out.println("String: " + s1);
StringBuilder s2 = new StringBuilder("Hello");
concat2(s2); // s2 is mutable therefore changed
System.out.println("StringBuilder: " + s2);
StringBuffer s3 = new StringBuffer("Hello");
concat3(s3); // s3 is also mutable therefore changed
System.out.println("StringBuffer: " + s3);
}
}

OUTPUT

String: Hello World
StringBuilder: Hello World
StringBuffer: Hello World

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.