Home » Core Java » Java String vs StringBuffer vs StringBuilder Example

About Bhagvan Kommadi

Bhagvan Kommadi
Bhagvan Kommadi is the Founder of Architect Corner & has around 18 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript.

Java String vs StringBuffer vs StringBuilder Example

1. Introduction

In this post, we feature a comprehensive article on Java String vs StringBuffer vs StringBuilder.

In an in-depth analysis we will feature how to create Strings and modify string objects using String class, StringBuffer class and StringBuilder class.

2. Java String vs StringBuffer vs StringBuilder

2.1 Prerequisites

Java 7 or 8 is required on the linux, windows or mac operating system.

2.2 Download

You can download Java 7 from Oracle site. On the other hand, You can use Java 8. Java 8 can be downloaded from the Oracle web site .

2.3 Setup

You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:

Run Command
JAVA_HOME=”/jboss/jdk1.8.0_73″
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

2.4 Java String

In java, strings are objects. String class is used to modify and change strings. String objects are created by initializing the instance by using constructor and new keyword. new keyword creates an instance of a String class as an Object. The constructor takes an argument as a string and creates a String Object.String objects created will be part of the String Constant Pool.String pool is important for String creation as object allocation is expensive in both time and memory. The pool of strings is maintained to reduce the number of strings created in the Java Virtual Machine. String class is immutable. A String instance which is created cannot be modified. The String methods create the String objects and return a new String object as an output of the methods. Sample Code is shown how String class is used. The StringDemo shows taking a String and reversing a String which is a palindrome. The StringDemo class has a method reversePalindrome which takes the input palindrome string and returns the reversed String.

String Demo
public class StringDemo {
    
    
    public String reversePalindrome(String palindrome)
    {
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 
        
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =
            new String(charArray);
        
        return reversePalindrome;
        
    }
    public static void main(String[] args) {
        
        String palindrome = "Red rum, sir, is murder";
        StringDemo stringReverser = new StringDemo();
        String reversePalindrome = stringReverser.reversePalindrome(palindrome);
        System.out.println(reversePalindrome);
    }
}

The command below executes the above code snippet:

String Demo
javac StringDemo.java
java StringDemo

The output of the executed command is shown below.

StringDemo

2.4.1 Concatenating Java Strings

String class has a concat method for appending two strings. Strings can be concatenated with the + operator. ConcatStringDemo class below shows the concatenation of strings.

Concat String Demo
public class ConcatStringDemo {
    
    public static void main(String[] args) {
        
        String firstString = "Red rum, sir, is murder";
        System.out.println("first string "+ firstString);
        String secondString = " added String";
        System.out.println("second string "+ secondString);
        String concatenatedStrings = firstString.concat(secondString);
        System.out.println("concatenated String "+concatenatedStrings);
    }
}

The command below executes the above code snippet:

Concat String Demo
javac ConcatStringDemo.java
java ConcatStringDemo

The output of the executed command is shown below.

ConcatString Demo

2.4.2 Formatting Java Strings

String class has format method which can take string which has integer, float, double and character data types. FormatStringDemo class shows below the formatting of the String which has integer, double and string data types.

Formatting String Demo
public class FormatStringDemo {
    
    public static void main(String[] args) {
        
       String formattedString;
       int intVal = 3;
       double doubleVal = 5.4;
       String stringVal = "formatted String";
       formattedString = String.format("The value of the int variable is " +
                   "%d, while the value of the double " +
                   "variable is %2.1f, and the string " +
                   "is %s", intVal, doubleVal, stringVal);
       System.out.println(formattedString);
    }
}

The command below executes the above code snippet:

Formatting String Demo
javac FormatStringDemo.java
java FormatStringDemo

The output of the executed command is shown below.

FormatString Demo

2.5 Java String Buffer

A StringBuffer cannot be changed like a String. It consists of a set of characters. StringBuffer methods are used to change the length and set of the characters in a String Buffer. Multiple Threads can access the String buffer and modify the String buffer simultaneously. String Buffer methods are synchronized and multiple threads can operate on the string buffer instance. StringBuffer has methods append and insert to modify the String. Sample Code is shown below how StringBuffer class is used.

String Buffer Demo
public class StringBufferDemo {
    
   public StringBuffer appendString(String initial, String buffer)
   {
       StringBuffer sBuffer = new StringBuffer();
       sBuffer.append(buffer);
       
       return sBuffer;
       
   }

   public static void main(String args[]) {
       
      StringBufferDemo stringBufferDemo = new StringBufferDemo();
       
      String initial = "check the string";
       
      System.out.println("initial String "+initial);
       
      StringBuffer sBuffer = stringBufferDemo.appendString(initial," added string");
       
      
      System.out.println(sBuffer);  
   }
}

The command below executes the above code snippet:

String Buffer Demo
javac StringBufferDemo.java
java StringBufferDemo

The output of the executed command is shown below.

StringBufferDemo

2.5.1 Creation of String Buffer

StringBuffer Class has constructors related to creation of StringBuffer by specifying size and by specifying the string. The below class StringBuffer CreationDemo shows the creation of StringBuffer using different Constructors.

String Buffer Creation Demo
public class StringBufferCreationDemo {

   public static void main(String args[]) {
       
      StringBuffer stringBuffer = new StringBuffer(30);
       
      stringBuffer.insert(0,"buff");
      
      System.out.println("after insertion "+stringBuffer);  
       
       
      StringBuffer sBuffer  = new StringBuffer("created String Buffer");
       
      System.out.println("string buffer"+sBuffer);
             
   }
}

The command below executes the above code snippet:

String Buffer Creation Demo
javac StringBufferCreationDemo.java
java StringBufferCreationDemo

The output of the executed command is shown below.

StringBufferCreation Demo

2.6 Java String Builder

StringBuilder class is used to build a mutable set of characters. StringBuffer is consistent with StringBuilder but synchronization is not guaranteed. StringBuilder can replace StringBuffer in scenarios which are single threaded. StringBuilder has the append and insert methods which can handle different types of data. This StringBuilderDemo class transforms the data into a string and adds or modifies the characters of the string in the StringBuilder. The sample code below shows how StringBuilder is used.

String Builder Demo
public class StringBuilderDemo {
    
    public StringBuilder reverseString(String palindrome)
    {
        StringBuilder sb = new StringBuilder(palindrome);
        
        StringBuilder reverse = sb.reverse();

        return reverse;
    }
    public static void main(String[] args) {
        String palindrome = "Red rum, sir, is murder";
         
          StringBuilderDemo stringBuilderDemo = new StringBuilderDemo();
        
          StringBuilder reverse = stringBuilderDemo.reverseString(palindrome);
        
          System.out.println(reverse);
    }
}

The command below executes the above code snippet:

StringBuilder Demo
javac StringBuilderDemo.java
java StringBuilderDemo

The output of the executed command is shown below.

StringBuilder Demo

2.6.1 Creation of String Builder

StringBuilder class has constructors to create the instances of StringBuilder by specifying the capacity and by specifying the string. StringBuilderCreationDemo class is shown below to demonstrate the creation of StringBuilder Objects by using the constructors.

String Builder Creation Demo
public class StringBuilderCreationDemo {
    

    public static void main(String[] args) {
        
        
        StringBuilder stringBuilder = new StringBuilder("build String");
        
        System.out.println("string built :"+ stringBuilder);
        
        
        StringBuilder initializedStringBuilder = new StringBuilder(30);
        
        System.out.println("initialized :"+ initializedStringBuilder);
        
        initializedStringBuilder.append("added String");
        
        System.out.println("built String after appending :" +initializedStringBuilder);
        
    }
}

The command below executes the above code snippet:

StringBuilderCreation Demo
javac StringBuilderCreationDemo.java
java StringBuilderCreationDemo

The output of the executed command is shown below.

StringBuilderCreation Demo

3. Download the Source Code

Download
You can download the full source code of this example here: Java String vs StringBuffer vs StringBuilder
(+4 rating, 4 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of