• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Selenium
  • Manual Testing
  • SQL Tutorial For Beginners
  • Difference
  • Tools
  • Contact Us
  • Search
SoftwareTestingo Â» Java Â» Java Tutorial Â» StringBuilder Class In Java with Examples

StringBuilder Class In Java with Examples

Last Updated on: July 10, 2023 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • What is StringBuilder in Java?
  • How does StringBuilder Work Internally?
  • StringBuilder Class Constructors
  • Methods of StringBuilder Class
  • What is the use of String builder?
  • Why do we use String builder in Java?
  • Is String builder efficient?:
  • Which is better: StringBuilder or String?:

StringBuilder Class In Java is used to create a changeable sequence of characters. Unlike the String class, which creates an unchangeable sequence of characters, StringBuilder allows us to modify the characters in the sequence.

It is similar to the StringBuffer class, as both provide an alternative to the String class by allowing changes to the character sequence. However, the main difference is that StringBuilder does not guarantee synchronization, while StringBuffer does.

StringBuilder is faster and more suitable for use in a single-threaded environment. If synchronization is needed for multiple threads, it is recommended to use StringBuffer. StringBuilder is not thread-safe but performs well compared to StringBuffer.

Post On:StringBuilder Class In Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

In this tutorial, we will use examples to learn about the StringBuilder class and its methods like append, reverse, delete, and toString.

What is StringBuilder in Java?

If you have the word “SoftwareTestingo” in a particular memory location, storing it in the StringBuilder class instead of the String class is better. This is because when new characters are added, no new memory is allocated each time as if you stored it in the String class. The StringBuilder class is mutable, meaning updating can be done within the sequence.

If we want to perform character manipulation, it’s better to use the StringBuilder class instead of the String class. Let’s take a closer look at some of the features of the StringBuilder class.

Syntax:

The StringBuilder class in Java allows you to create mutable strings. This means that you can change the value of a string after it has been created. This class extends the Object class, the parent class of all predefined and user-defined classes in Java.

The Class hierarchy is like this:

StringBuilder Class Hierarchy

The StringBuilder class contains methods like hashCode() and equals(), and implements the two interfaces, Serializable and CharSequence. These features allow for different types of character sequences to be implemented.

The Syntax Of the StringBuilder Class is:

public final class StringBuilder
    extends Object
    implements Serializable, CharSequence
StringBuilder Syntax
StringBuilder Syntax

How does StringBuilder Work Internally?

What will happen when the Buffer gets full? A new Buffer that is double the size of the older buffer is automatically created. No new memory is allocated for every update. Also, StringBuilder is not synchronized, meaning multiple threads can access the StringBuilder object simultaneously. Therefore, StringBuilder is not a thread-safe class.

StringBuilder Class Constructors

The StringBuilder class provides different types of constructors that help convert an ordinary sequence of characters to a StringBuilder format and configure properties such as size. Let’s discuss the different constructors one by one.

StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16 characters. The maximum number of characters that a StringBuilder object can store is known as the capacity of the StringBuilder.

Syntax:

StringBuilder obj=new StringBuilder();

Example:

package com.softwaretestingo.stringbuilder;
public class StringBuilderEx 
{
	public static void main(String[] args) 
	{
		StringBuilder obj = new StringBuilder("Software Blog");
		obj.insert(8, "Testingo");

		System.out.println(obj);
	}
}

Output:

SoftwareTestingo Blog

StringBuilder(int capacity): This constructor initializes a new instance of the StringBuilder class with no characters in it and the specified capacity. The following is the syntax for this constructor.

Syntax:

StringBuilder obj=new StringBuilder(10);
package com.softwaretestingo.stringbuilder;
public class StringBuilderEx2 
{
	public static void main(String[] args) 
	{
		StringBuilder obj = new StringBuilder(10);

		// print string
		System.out.println("Object capacity = "+ obj.capacity());
	}
}

Output:

Object capacity = 10


StringBuilder(CharSequence seq): This constructor is used for creating a StringBuilder of char sequence. The char sequence is the sequence of characters in a string.

StringBuilder obj=new StringBuilder(CharSequence);
package com.softwaretestingo.stringbuilder;
public class StringBuilderEx4 
{
	public static void main(String[] args) 
	{
		StringBuilder obj = new StringBuilder("AAAABBBCCCC");

		// print string
		System.out.println("String1 = "+ obj.toString());
	}
}

Output:

String1 = AAAABBBCCCC

StringBuilder(String str): Constructs a string builder initialized to the contents of the specified string.

Syntax:

StringBuilder ob=new StringBuffer(String);
package com.softwaretestingo.stringbuilder;
public class StringBuilderEx5 
{
	public static void main(String[] args) 
	{
		StringBuilder obj = new StringBuilder("AAAABBBCCCC");

		// using StringBuilder(String) constructor
		StringBuilder obj1= new StringBuilder(obj.toString());

		// print string
		System.out.println("Object 1 = "+ obj1.toString());
	}
}

Output:

Object 1 = AAAABBBCCCC

Methods of StringBuilder Class

The StringBuilder class provides a variety of inbuilt methods that can be used to perform different operations on Strings. Let’s discuss each method one by one.

append(): This method attaches the passed string at the end of the existing string.

This method takes one parameter. This method adds a specified value to the end of a StringBuilder sequence. The value can be any data type.

package com.softwaretestingo.stringbuilder;
public class StringBuilderEx6 
{
	public static void main(String[] args) 
	{
		StringBuilder first = new StringBuilder("Software");
		first.append("Testingo");
		System.out.println("After Append: "+first);

		first.append(111);
		System.out.println("After Adding Different Datatype: "+first);
	}
}

Output:

After Append: SoftwareTestingo
After Adding Different Datatype: SoftwareTestingo111

Insert(): The capacity of a StringBuilder object can be found using this method. The default capacity of the StringBuilder class is 16 bytes. If the capacity is full, the new capacity will be current (capacity+1)*2.

package com.SoftwareTestingO.Strings;
public class StringBuilderEx3 
{
	public static void main(String[] args) 
	{
		StringBuilder first = new StringBuilder();
		System.out.println("Default Capacity: "+first.capacity());

		//Capacity increase by (16(default capacity)+1)*2=34
		first.append("aaaaaaaaaaaaaaaaaa");
		System.out.println("After Full, New Capacity: "+first.capacity());
	}
}

substring() method:

Converting The StringBuilder Object to a String

Never fear if you need to change your StringBuilder object into a regular ol’ string! The StringBuilder class provides a method, StringBuilder.toString(), which does just that.

package com.SoftwareTestingO.Strings;
public class StringBuilderEx4 
{
	public static void main(String[] args) 
	{
		StringBuilder first = new StringBuilder();
		first.append("SoftwareTestingo");
		
		//Convert Stringbuilder to String
		System.out.println(first.toString());
	}
}

What is the use of String builder?

The StringBuilder class is useful for storing mutable elements. This saves memory because no extra memory is used after updating the StringBuilder sequence.

Why do we use String builder in Java?

One of the main reasons is StringBuilder is not thread-safe which means When multiple threads can access a StringBuilder object, it increases performance because no thread has to wait for their turn for a particular operation.

Is String builder efficient?:

Yes, StringBuilder is efficient because due to the mutable and non-thread-safe property of the StringBuilder.

Which is better: StringBuilder or String?:

StringBuilder is better because it is 6000 times faster than the String class.

    Polymorphism In Java
    Polymorphism In Java
    List Interface In Java
    List Interface In Java
    Exception Hierarchy In Java
    Exception Hierarchy In Java
    Deque In Java
    Deque In Java
    Java Switch Case Statement
    Java Switch Case Statement
    Map In Java
    Map In Java
    String Pool in Java SoftwareTestingo
    String Pool in Java
    Memory Management In Java
    Memory Management In Java
    Abstraction in java
    Define Data Abstraction in java & Abstract Class With Real...
    Static Keyword In Java
    Static Keyword In Java

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

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

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Footer

    Java Tutorial for Beginners | Selenium Tutorial | Manual Testing Tutorial | SQL Tutorial For Beginners | GitHub Tutorial For Beginners | Maven Tutorial

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers