Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a String?
3.
What is a StringBuffer?
4.
Comparison
5.
Performance Test
6.
HashCode Test
7.
Frequently Asked Questions
7.1.
Are Strings in Java mutable?
7.2.
Which type of memory does StringBuffer use to store objects?
7.3.
What is the equals() method?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Strings vs StringBuffer

Author Nagendra
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java is one of the most popular programming languages. Learning Java reinforces essential computer science principles while also providing access to a wide range of professional options.
A string is a collection of characters in Java, while a char is a single number used to hold variables. The StringBuffer is a String companion class that provides a lot of the same functionality as strings. StringBuffer represents growable and writable character sequences, whereas string represents fixed-length, immutable character sequences.

Let's take a quick discussion about the string and string buffer before we go over the comparison between them.

Recommended Topic-  Iteration Statements in Java, and Duck Number in Java.

What is a String?

The string is an immutable class, which means that its object can't be changed after it's been formed, although it can reference other objects. Immutable objects are thread-safe in multithreading environments because many threads cannot change the state of the object. Arrays are unchangeable in Java, and strings are as well. In any instance, if a string is modified, a whole new string is created.

Some facts about Strings are : 

  • The index of strings starts from 0.
  • String objects are immutable.

Take a look at the example below to see how to convert all letters in a string to uppercase.

Code

public class Lower_Case {
   public static void main(String args[]) {
      String s = "STRING LOWER CASE";
	/*s.setCharAt(1,"A"); //This will result in error as String is immutable*/
      System.out.println(s.toLowerCase());
   }
}

Output

string lower case

Explanation:

The toLowerCase() is a String class predefined function that returns all letters to lowercase.

Also see, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is a StringBuffer?

StringBuffer is a String companion class that provides a lot of the same functionality as strings. StringBuffer represents growable and writable character sequences, whereas string represents fixed-length, immutable character sequences. Characters and substrings can be placed in the middle or appended to the end of a StringBuffer. It will automatically expand to accommodate such additions, and it will frequently have more characters preallocated than are actually required to allow for future expansion.

Code

public class Mutable {
   public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("STRING LOWER CASE");
      sb.setCharAt(1,'A'); //Changes the character at index 1 to A
      System.out.println(sb);
   }
}

Output

SARING LOWER CASE

Explanation

The setCharAt() method in the preceding code changes the character at index 1 to A, demonstrating that the Stringbuffer is Mutable.

To further comprehend the concept, let's compare String with StringBuffer.

Check this out, Solid Principles in java

Comparison

So far, we've learned about String and StringBuffer. The key distinctions between string and StringBuffer are listed in the table below.

Let's look at the difference between the time taken by the performance test to conduct the concatenation operation.

Also see, Difference Between Rank and Dense Rank

Performance Test

With the help of the following code snippet, we will see how the time taken to perform a concatenation operation by String, and StringBuffer differs.

Code

public class ConcatTest
{  
    public static String concate_String()
    {  
        String s = "Concatinating";  
        for (int i=0; i<500; i++)
        {  
            s = s + "string";  
        }  
        return s;  
    }  
    public static String concate_StringBuffer()
    {  
        StringBuffer sb = new StringBuffer("Concatinating");  
        for (int i=0; i<500; i++)
        {  
            sb.append("string");  
        }  
        return sb.toString();  
    }  
    public static void main(String[] args)
    {  
        long start_time = System.currentTimeMillis();  
        concate_String();  
        System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-start_time)+"ms");  
        start_time = System.currentTimeMillis();  
        concate_StringBuffer(); //Concating string with string buffer
        System.out.println("Time taken by Concating with StringBuffer: "+(System.currentTimeMillis()-start_time)+"ms");  
    }  
}  

Output:

Time taken by Concating with String: 66ms
Time taken by Concating with StringBuffer: 0ms

Explanation:

Using the String and StringBuffer classes, the given code calculates the time required to concatenate a string. (The values may vary with the different compilers)

Check out this article - C++ String Concatenation and Hashcode Method in Java.

HashCode Test

The hashCode() method is used to offer a numeric representation of an object's contents as an alternative way for identifying it.With the help of the following code snippet, we will see how the result of HasCode test String and StringBuffer differs.

Code:

public class HashCode_Test
{  
    public static void main(String args[])
    {  
        System.out.println("String HashCode test:");  
        String s="String";  
        System.out.println(s.hashCode());  
        s=s+"Check";  
        System.out.println(s.hashCode());  
        System.out.println("StringBuffer HashCode test:");  
        StringBuffer sb=new StringBuffer("String");  
        System.out.println(sb.hashCode());  
        sb.append("Check");  
        System.out.println(sb.hashCode());  
    }  
}  

Output:

String HashCode test:
-1808118735
131309399
StringBuffer HashCode test:
1746572565
1746572565

Explanation:

We observe that after performing concatenation, String returns a new hashcode, whereas the StringBuffer class returns the same hashcode. Try this code by yourself on Online Java Compiler.

Must Read String Args in Java

Frequently Asked Questions

Are Strings in Java mutable?

No, Strings in Java are immutable.

Which type of memory does StringBuffer use to store objects?

The StringBuffer stores the objects in heap memory.

What is the equals() method?

The equals() method is used when two strings are compared; it returns true if they are equal and false if they are not.

Conclusion

In this article, we have extensively discussed the difference between String and StringBuffer along with the HashCode test and performance test to examine the difference between the time taken in the execution of concatenating operation.
We hope that this blog has helped you enhance your knowledge regarding the difference between String and StringBuffer, and if you would like to learn more, check out our articles on Java. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Do upvote our blog to help other ninjas grow. 

Happy Coding!!

Previous article
String Class Methods
Next article
StringBuffer Class
Live masterclass