Easy tutorial on Java String, StringBuilder and StringBuffer

Gaurav Sharma
CodeX
Published in
6 min readApr 28, 2022
Photo by Henry Be on Unsplash

In this tutorial, we are going to dive deep into the concepts of Java String, StringBuilder and StringBuffer and understand what class we should use and when.

Strings are extensively used as a data type and it allows the programmer to handle words, sentences, phone numbers, or even just usual numbers. Fundamentally String is an object that represents a sequence of character values.

STRING CLASS

Java String class is a standard class that comes with Java and is specifically used to handle strings. Java string class implements Serializable, Comparable, and CharSequence interfaces. An array of characters also works the same way as a Java string. For example:

char[] ch = {‘j’, ‘a’, ‘v’ , ‘a’};

String str = new String(ch);

This will initialise a new string that will have java as its content.

The above two lines can be written as

String str = ”java”;

Our first way of initialising a string showed us that strings contain an array of characters.

Java Strings are said to be immutable. Immutable means unmodifiable or unchangeable which means once a string object is created then we can not change its content.

Below we can see an example depicting this fact.

Here Gaurav is not changed but a new object is created with Gaurav Sharma. That is why String is known as immutable.

But if we explicitly assign it to the reference variable, it will refer to the Gaurav Sharma object.

Here we changed the reference of variable s to string “Gaurav sharma” from “Gaurav”

Operations with strings

There are many operations that we can perform with strings I am going to list the most important here.

  1. String concatenation:
    This section deals with joining two or more strings using different techniques
  • String concatenation using + operator

We can join two Strings using the + operator and it’ll return a String which will have the contents of both of the strings appended to each other.

But + operator can lead to ambiguity in the case of concatenating strings with numbers let's understand this point with an example.

In this example, we can see that concatenation works strange enough to make us think again about the output

Here we got the output 50TestString2040 because the string concatenation using + creates a new string and it keeps appending operands onto the end of the preceding operands.

Let’s understand this statement a little bit more by using step by step approach.

The statement10+20+20+s1+s2+20+40 works as follows.

10+20=30
30+20=50
50+s1=50Test
50Test+s2=50TestString
50TestString+20=50TestString20
50TestString20+40=50TestString2040

NOTE: An integer appended to the string will always result in a string.

  • String concatenation by concat method:

2. Comparing Strings

Various techniques are used to check the equality of strings in terms of values and the reference. There are 3 ways in java to compare string values.

  • String compare by equals method

The String equals method compares the strings based on their contents. It compares strings for parity or equality.

String class provides 2 methods for comparison of contents.

public Boolean equals(String str)
public Boolean equalsIgnoreCase(String str)

equals method compares two strings normally but it also takes account of the case too

“Apple” != “apple”

but in the case of equalsIgnoreCase the statement will be true

“Apple” == “apple”

  • String comparison by == Operator

The == operator compares the reference or memory location of objects in a heap. It doesn’t check for the value it checks for reference.

  1. s1==s2 is true because both have the same addresses in the string constant pool. To know more about string constant pool please refer to this link because this topic is large and out of the scope of this tutorial.
    https://www.geeksforgeeks.org/string-constant-pool-in-java/
  2. s1==s3 is false because whenever we are creating a string object with the new keyword we are allocating a new memory location in the string constant pool for this object so s1 and s3 don’t refer to the same memory location in the heap.
  • String compare with compareTo() method

The compareTo() method compares both of the strings lexicographically and returns an integer value that indicates the first string is less than, equal or greater than the second string. For two strings s1 and s2 if

s1==s2 returns 0
s1>s2 returns positive number
s1<s2 returns negative number

Here we can see that the compareTo method checks only the relative ordering of letters in two strings.

Some important methods of String class

STRINGBUFFER CLASS

The String and StringBuffer classes are defined in java.lang package. StringBuffer class is used to create a mutable or modifiable string. Everything is the same in String and StringBuffer except that the StringBuffer class represents a growable and writeable sequence of characters. It is possible to replace any character in the StringBuffer and we can also insert characters in the StringBuffer and the StringBuffer will grow in size by itself.

We can declare StringBuffer in 3 ways (it has 3 constructors) and we are going to see all of them.

  1. StringBuffer str = new StringBuffer();
    This will create a StringBuffer object which is an empty string buffer with an initial capacity of 16 characters.
  2. StringBuffer str = new StringBuffer(String string);
    This will create a StringBuffer object with the content of the string passed as the parameter.
  3. StringBuffer str = new StringBuffer(int size);
    It will create an empty StringBuffer object with an initial size equal to that integer passed as the parameter.

StringBuffer Methods:

Some methods make Stringbuffers stand out from Strings and we are going to discuss them in detail

  • append():

The append method appends the given argument to the string. It takes 3 types of arguments String, int, and Object.

Syntax:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

Example:

  • insert()

The insert() method inserts the given string, character, or object into another string at the given position.

Syntax:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

Example:

  • delete()

The delete() method is used to delete a character from the string at an index or we can delete characters in a range.

Syntax:
StringBuffer insert(int startIndex, int endIndex)

Example:

  • reverse()

This method reverses the string. It does the in-place reversal of the string.

Syntax:
StringBuffer reverse()

Example:

  • capacity()

The capacity() method of the StringBuffer class in Java is used to return buffer capacity. By default, a string buffer has a 16 character capacity. By calling this method, we can calculate its current capacity.

If the number of characters is increased by the current capacity Stringbuffer increases its size by (current capacity*2)+2

Example:

STRINGBUILDER CLASS

StringBuilder class is used to create mutable and modifiable strings same as the StringBuffer class but the only difference between StringBuffer and StringBuilder is that StringBuffer is synchronized. All the methods of StringBuffer are available in StringBuilder.

DIFFERENCES BETWEEN STRING AND STRINGBUFFER CLASS

String

  1. The String class is immutable.
  2. String is slow and consumes more memory when we concatenate too many strings because every time it creates a new instance.
  3. String class overrides the equals() method of the Object class. So you can compare the contents of two strings by the equals() method.
  4. String class is slower while performing concatenation operations.
  5. String class uses String constant pool.

StringBuffer

  1. StringBuffer is fast and consumes less memory when we concatenate two strings.
  2. StringBuffer class doesn’t override the equals() method of the Object class.
  3. StringBuffer class is faster while performing concatenation operations.
  4. The StringBuffer class is mutable.
  5. StringBuffer uses Heap memory.

DIFFERENCES BETWEEN STRINGBUILDER AND STRINGBUFFER CLASS

StringBuffer

  1. StringBuffer is synchronized i.e. thread-safe. It means two threads can’t call the methods of StringBuffer simultaneously.
  2. StringBuffer is less efficient than StringBuilder.
  3. StringBuffer was introduced in Java 1.0

StringBuilder

  1. StringBuilder is non-synchronized i.e., not thread-safe. It means two threads can call the methods of StringBuilder simultaneously.
  2. StringBuilder is more efficient than StringBuffer.
  3. StringBuilder was introduced in Java 1.5

So this is all about String, StringBuffer and StringBuilder classes here we learned what these classes are, what they can do, and what they cannot do. I hope you enjoyed reading and learning about these classes in deep.

If you understood anything I said here please give a clap reaction and follow me because it helps me to stay motivated and take out time from my schedule to write these articles. It will not cost you anything but will help me a lot

Gaurav sharma is an avid reader and a passionate traveller. He is trying to live a more meaningful and purposeful life by spreading his knowledge and his life experiences! Follow him on this new journey of balancing digital and physical life. He is living in Uttarakhand, India. He is on Instagram at @golf._.sierra

--

--