You are on page 1of 1

Sign in Get started

WRITE FOR US CODING INTERVIEW COURSE →


Level Up Coding
Coding tutorials and
news.
You have 2 free stories left this month. Sign up and get an extra one for free.
Follow

String, StringBuilder, and


StringBu er: A Complete Guide
Know text/string manipulation classes in Java, how, and when to use
them.

Vikram Gupta Follow


Sep 27 · 4 min read

Photo by Sincerely Media on Unsplash

. . .

When it comes to text/string manipulation developers think of String,


StringBuilder, and StringBuffer classes but sometimes new developers
working on Java get confused with these string classes.

Java programming language provides three string classes: String,


StringBuilder, and StringBuffer in java.lang package.

So this article is all about String, StringBuilder, and StringBuffer classes


and how to use them, when to use them, and their methods.

. . .

1. String :
The String class represents character strings. All string literals in Java
programs, such as “ABC”, are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are Top highlight

created. Because String objects are immutable they can be shared


between multiple threads. So string objects are good for a multi-
threaded environment as there won’t be data inconsistencies.

There are two ways to create string objects: Using string literal and
other is using a new keyword.

The + operator is overloaded for String. It is used for concatenating two


strings. Internally it uses StringBuffer to perform concatenation.

Let’s see an example :

1
2 public class StringExample {
3
4 public static void main(String[] args) {
5 String name1 = "Vikram";
6 //here string literal used to create string object
7
8 String name2 = new String("Gupta");
9 //here new keyword is used to create string object
10 }
11 }

StringExample.java hosted with ❤ by GitHub view raw

String object creation example

1. When string literal is used to create a string object first it checks


whether this string already exists in String Pool. String Pool is a set of
string constants that sits in the heap area. If the string already exists in
this String Pool then a reference is returned else a new string object is
created in this pool and the reference of this newly created object is
returned.

2. When a new keyword is used to create a string object it always creates


an object in the heap area and a reference of this object is returned.
While creating a string object in the heap area it checks if this string
object is present in String Pool or not. If the string object is not present
in String Pool then it creates a new object in String Pool as well. But the
newly created string variable will always point to the string object in the
heap and not in the String Pool.

In the below program I’ve explained about these two points :

1
2 public class Main {
3
4 public static void main(String[] args) {
5
6 String name1 = "Tom";
7 String name2 = "Tom";//name1.intern();
8
9 String name3 = new String("Bob");
10 String name4 = "Bob";
11
12 System.out.println(name1 == name2);
13 System.out.println(name3 == name4);
14
15 }
16 }

Main.java hosted with ❤ by GitHub view raw

String Pool Example

OUTPUT :

true
false

The above program can be understood using this diagram :

String Pool and Heap Area example

Below are String class methods. They can be used as an individual method
or in combination.

length(), equals(), substring(), charAt(), concat(), replace(),


trim(), split(), toUpperCase(), toLowerCase()

. . .

2.StringBuilder :
StringBuilder represents a mutable sequence of characters.

The instance of this class does not guarantee Synchronization and hence
should not be used in multi-threaded environments.

Wherever possible we should always try to use StringBuilder instead of


StringBuffer as StringBuilder is faster than StringBuffer under most
implementations.

Below are StringBuilder class methods and descriptions. They can be used
as an individual method or in combination.

1. append(): Appends the string representation of the specified argument


to the specified StringBuilder instance sequence.

2. insert(): Inserts the string representation of the specified argument to


the specified StringBuilder instance sequence.

1
2 public class Main {
3
4 public static void main(String[] args) {
5
6 StringBuilder stringBuilder = new StringBuilder("Vikram");
7 System.out.println(stringBuilder);
8 stringBuilder.append(" Gupta");
9 System.out.println(stringBuilder);
10 stringBuilder.insert(7," Binod");
11 System.out.println(stringBuilder);
12 }
13 }

Main.java hosted with ❤ by GitHub view raw

String builder example

OUTPUT:

Vikram
Vikram Gupta
Vikram Binod Gupta

Note: insert method can be used for appending the string at the end of
the specified string using the length() function.

stringBuilder.insert("Vikram".length()," Gupta");
//this results "Vikram Gupta"

. . .

3.StringBuffer :
StringBuffer class represents a thread-safe, mutable sequence of
characters.

A string buffer is like a String but it can be modified. At any point in


time, it contains some particular sequence of characters, but the length
and content of the sequence can be changed through certain method
calls.

The methods of StringBuffer class are synchronized where necessary so


that all the operations on any particular instance behave as if they occur
in some serial order that is consistent with the order of the method calls
made by each of the individual threads involved.

The principal operations on a StringBuffer instance are the append and


insert methods, which are overloaded so as to accept data of any type.
Each converts a given data to a string and then appends or inserts the
characters of that string to the string buffer.

The append method always adds these characters at the end of the
buffer and the insert method adds the characters at a specified point.

Below are StringBuffer class methods and descriptions. They can be used as
an individual method or in combination. These methods are synchronized
and can be used for a multi-threaded environment.

1. append(): Appends the string representation of the specified argument


to the specified StringBuffer instance sequence.

2. insert(): Inserts the string representation of the specified argument to


the specified StringBuffer instance sequence.

Let’s see an example :

1 public class Main {


2
3 public static void main(String[] args) {
4
5 StringBuffer stringBuffer = new StringBuffer("Vikram");
6 System.out.println(stringBuffer);
7 stringBuffer.append(" Gupta");
8 System.out.println(stringBuffer);
9 stringBuffer.insert(7, "Binod ");
10 System.out.println(stringBuffer);
11 }
12 }

Main.java hosted with ❤ by GitHub view raw

String bu er example

OUTPUT:

Vikram
Vikram Gupta
Vikram Binod Gupta

. . .

StringBuider Vs StringBuffer performance testing :


I did a performance test for both StringBuilder and StringBuffer instance
using the append method. It results out that StringBuilder is faster than
StringBuffer.

1
2 import java.util.Calendar;
3
4 public class Main {
5
6 public static void main(String[] args) {
7
8 System.gc();
9 StringBuilder stringBuilder = new StringBuilder("Vikram");
10 long startTime1 = Calendar.getInstance().getTimeInMillis();
11 for (long i = 0; i < 10000000; i++) {
12 stringBuilder.append(i);
13 }
14 long endTime1 = Calendar.getInstance().getTimeInMillis();
15 System.out.println("Time taken for 10000000 appends for StringBuilder:" + (endTime1 - st
16
17 System.gc();
18 StringBuffer stringBuffer = new StringBuffer("Vikram");
19 long startTime2 = Calendar.getInstance().getTimeInMillis();
20 for (long i = 0; i < 10000000; i++) {
21 stringBuffer.append(i);
22 }
23 long endTime2 = Calendar.getInstance().getTimeInMillis();
24 System.out.println("Time taken for 10000000 appends for StringBuffer:" + (endTime2 - sta
25
26 }
27 }

Main.java hosted with ❤ by GitHub view raw

StringBuilder and StringBu er example

OUTPUT:
The below out is an average of 20 runs and we can see the difference.

Time taken for 10000000 appends for StringBuilder:638 ms


Time taken for 10000000 appends for StringBuffer:771 ms

. . .

That’s it for this article. I hope you have understood the concept of String,
StringBuilder, and StringBuffer. If you find this article helpful, you can
follow me.

You can read my other helpful articles on Java Programming.

What does String Pool mean in Java?


In this article, I’m going to cover String Pool and no of objects created when
double quotes and new operators are used…

medium.com

Confused With Enum? Here Is an Article to Clear It.


Hey, in this article I’m going to explain enum, enum instance variables,
constructors, and instance methods.Enum…
medium.com

How to Write Clean Code? Follow These Best Practices


Hey programmers, this article is not about some java related feature or
concept but more than that. Basically, I’m…
medium.com

String Stringbuilder Stringbu er Software Development Java Programming

WRITTEN BY
Vikram Gupta Follow

| Software Developer | Programming enthusiast | Loves Data


Structures and Algorithms | LinkedIn : https://bit.ly/3ivmZzU

Level Up Coding Follow

Coding tutorials and news. The developer homepage


gitconnected.com

More From Medium

How we wrote the Why I Am Relearning This is What it Takes to Replacing If-Else With
Fastest JavaScript UI Angular Be a Great Front-End Commands and Handlers
Framework, Again! Bharath Ravi in Level Up Developer These Days Nicklas Millard in Level Up
Ryan Carniato in Level Up Coding Daan in Level Up Coding Coding
Coding

Write Clean Code With Use VSCode Like a Senior 10 Useful Golang 4 Things You Have to
These 5 Simple Tips Developer Modules Developers Unlearn to Become A
Daan in Level Up Coding bit sh in Level Up Coding Should Know. Better Programmer
Bryan Dijkhuizen, BA. in Level Li-Hsuan Lung in Level Up
Up Coding Coding

Discover Medium Make Medium yours Become a member


Welcome to a place where words matter. On Medium, smart Follow all the topics you care about, and we’ll deliver the Get unlimited access to the best stories on Medium — and
voices and original ideas take center stage - with no ads in best stories for you to your homepage and inbox. Explore support writers while you’re at it. Just $5/month. Upgrade
sight. Watch

About Help Legal

You might also like