0 0
WP Ad Inserter plugin
Read Time:8 Minute, 52 Second

Table of Contents

StringBuilder is a Java class that allows you to generate a mutable, or changeable, sequence of characters. The StringBuilder class, like StringBuffer, is an alternative to the Java Strings class, which provides an immutable sequence of characters. However, there is a critical distinction between StringBuffer and StringBuilder: the latter is non-synchronized. It means that while working with a single thread in Java, StringBuilder is a better choice than StringBuffer because it is faster.

Java StringBuilder

StringBuilder is a changeable character sequence. When we need to edit Java strings in place, we use StringBuilder. On the hand, StringBuffer is a thread-safe version of StringBuilder that is similar to StringBuilder. StringBuilder provides methods for modifying strings, such as append, insert, and replace.

StringBuilder’s class declaration

The java.lang.StringBuilder class is part of the java.lang package and its declaration are as follows:

public class StringBuilder extends Object implements CharSequence, Serializable

Examining StringBuilder’s Constructors in Java

The constructors of StringBuilder in Java are listed and described in the table below.

StringBuilder()

It creates a blank string constructor with a 16-character capacity.

SUGGESTED READ

StringBuilder(int capacity)

It makes an empty string constructor with the capacity provided.

StringBuilder(CharSequence seq)

It generates a string builder that contains the same characters as the given arguments.

StringBuilder(String str)

The string supplied in the argument will create a string builder.

Now that you’ve learned about StringBuilder’s constructors and class declaration in Java let’s look at an example where you’ll use some of these constructors to produce various character sequences.

SUGGESTED READ

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; public class CodeStringBuilder{ public static void main(String[] args) throws Exception{ // using the constructor: StringBuilder()
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("CodeUnderscored");
System.out.println("String ="+ stringBuilder.toString()); // using the constructor: StringBuilder(CharSequence seq)
StringBuilder sbOne = new StringBuilder("Code in Scala");
System.out.println("String one ="+stringBuilder.toString()) //using the constructor: StringBuilder(int capacity)
StringBuilder sbTwo = new StringBuilder(32);
System.out.println("String two capacity ="+sbTwo.capacity()) // using the constructor: StringBuilder(String)
StringBuilder sbThree = new StringBuilder(stringBuilder)
System.out.println("String three ="+stringBuilder.toString()) }
}

Discussion of the Various StringBuilder Methods in Java

The StringBuilder class in Java uses several methods to conduct various actions on the string builder. The section below shows some of the StringBuilder class’s most important methods.

StringBuilder append (String s)

This method adds the specified string to the end of the existing string. You can also use boolean, char, int, double, float, and other parameters.

StringBuilder insert (int offset, String s)

It will insert the provided string from the specified offset position into the other string. You can overload this function with arguments like (int, boolean), (int, int), (int, char), (int, double), (int, float), and so on, just like you can with append.

StringBuilder replace(int start, int end, String s)

From the start index to the last index, it will replace the original string with the provided string.

StringBuilder delete(int start, int end)

This method removes the text from the specified start index to the specified end index.

SUGGESTED READ

StringBuilder reverse()

It is responsible for the reversal of the string.

int capacity()

It will display the StringBuilder’s current capacity.

void ensureCapacity(int min)

This method ensures that the StringBuilder’s capacity meets the specified minimum.

char charAt(int index)

The character in the provided index is returned.

int length()

This technique is used to get the string’s length (total characters).

SUGGESTED READ

String substring(int start)

This method will return the substring starting at the supplied index and ending at the specified index.

String substring(int start, int end)

It will return the substring between the start and end indexes.

int indexOf(String str)

The index of the first instance of the provided string will be returned by this method.

int lastIndexOf(String str)

It will return the index of the last occurrence of the provided string.

Void trimToSize()

It will attempt to shrink the StringBuilder.

SUGGESTED READ

Using StringBuilder’s Methods in Java

Let’s explore some of the StringBuilder methods in action.

Using StringBuilder’s Append() Method in Java

In the example below, you must use the append() method to concatenate three strings.

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder("Codeunderscored ") strBuilder.append("Java"); // The initial changes to the original String System.out.println(strBuilder); strBuilder.append("programming"); new updated changes to the updated string System.out.println(strBuilder); }
}

Using the Insert() Method to Insert a String

You will insert one string into another at the specified index in this example.

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder("Codeunderscored Java ") strBuilder.insert(4,"Coding"); // posion coding after Java System.out.println(strBuilder) }
}

Using StringBuilder’s Replace() Method in Java

To change Codeunderscored, use the replace() method to input Java from a defined start and end index.

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder("Codeunderscored Java coding ") strBuilder.replace(4,8,"Exposure"); // posion coding after Java System.out.println(strBuilder) }
}

Taking a Substring from the Original String and deleting it

In the example below, the remove() method will delete some strings based on the supplied indexes.

SUGGESTED READ

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder("Codeunderscored ")
strBuilder.delete(1,6);
System.out.println(strBuilder) }
}

Using StringBuilder’s Reverse() Method in Java

You’ll use the reverse() technique in the example below to reverse “Codeunderscored .”

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder("Codeunderscored ") strBuilder.reverse(); System.out.println(strBuilder) }
}

Investigating the Capacity() Method

The capacity() method determines a StringBuilder’s current capacity. The capacity is 16 by default. When there are more than 16 characters, the capacity is increased to n*2+2, where n is the current capacity. Let’s examine the example below.

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder("Codeunderscored ") strBuilder.append("coding script "); System.out.println(strBuilder) System.out.println("The volume is:", strBuilder.capacity()) strBuilder.append("Lets see if the code snippet expands") System.out.println(strBuilder) System.out.println("The volume is:", strBuilder.capacity()) }
}

Guaranteeing attainment of minimum capacity using the Ensurecapacity() method

In this example, you’ll utilize the StringBuilder’s ensureCapacity() method to check for the minimum capacity before proceeding with subsequent operations.

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder("Codeunderscored ") strBuilder.append("coding script "); System.out.println(strBuilder) System.out.println("The volume is:", strBuilder.capacity()) strBuilder.append("Lets see if the code snippet expands") System.out.println(strBuilder) System.out.println("The volume is:", strBuilder.capacity()) strBuilder.ensureCapacity(14) ; //no foreseable changes because the current capacity is greater System.out.println("The volume is:", strBuilder.capacity()) strBuilder.ensureCapacity(37) ; System.out.println("The volume is:", strBuilder.capacity()) }
}

Using Stringbuilder’s Length() Method in Java

The length() method is used in this example to determine the total number of characters in a string.

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder()
strBuilder.append("coding script in Python ");
System.out.println(strBuilder)
System.out.println(strBuilder.length()) }
}

Exploring the Charat() method

You can find the character at the specified index in the string using the charAt() method.

SUGGESTED READ

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder() strBuilder.append("coding script in Python "); System.out.println(strBuilder) System.out.println(strBuilder.charAt(7)) }
}

StringBuilder’s Indexof() Method in Java

Then, from the original string, use the indexOf() method to retrieve the index of the provided string.

public class CodeExample{ public static void main(String args[]){ StringBuilder strBuilder = new StringBuilder() strBuilder.append("coding script in Python "); System.out.println(strBuilder) System.out.println(strBuilder.indexOf("cript")) }
}

Example: code illustrating the StringBuilder methods

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; public class CodeUnderscored { public static void main(String[] argv) throws Exception { // creation of a StringBuilder object using a String pass as parameter StringBuilder strBuilder= new StringBuilder("CODE"); // show the string System.out.println("String = " + strBuilder.toString()); // reversing the string StringBuilder strReversal = strBuilder.reverse(); // print string System.out.println("Reverse String = "+ strReversal.toString()); // Appending the number ', '(73) to the given String strBuilder.appendCodePoint(73); // Print the modified String System.out.println("Modified StringBuilder = "+ strBuilder); // fetching the capacity int infCapacity = strBuilder.capacity(); // print the result System.out.println("StringBuilder = " + strBuilder); System.out.println("Capacity of StringBuilder = "+ infCapacity); }
}

Example: Code for illustrating the StringBuilder in Java

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; public class CodeUnderscored { public static void main(String args[] ) throws Exception { // Creation of StringBuilder's instance using the constructor StringBuilder() StringBuilder strBuilder = new StringBuilder(); str.append("CODE"); // showing the resultant string System.out.println("String = " + strBuilder.toString()); // create a StringBuilder object // using StringBuilder(CharSequence) constructor StringBuilder strBuilderOne	= new StringBuilder("AAAABBBCCCC"); // showing the resultant string System.out.println("String1 = " + strBuilderOne.toString()); // creation of an object instance of the StringBuilder // using StringBuilder(capacity) constructor StringBuilder strBuilderTwo = new StringBuilder(10); // showing the resultant string System.out.println("String2 capacity = "+ strBuilderTwo.capacity()); // creating an instance of the StringBuilder by using the constructor StringBuilder(String) StringBuilder strBuilderThree = new StringBuilder(strBuilderTwo.toString()); // showing the resultant string System.out.println("The third String is = " + strBuilderThree.toString()); }
}

Conclusion

You’ve learned everything there is to know about StringBuilder in this StringBuilder Java article. At the top of the list are the StringBuilder class’s constructors and functions. StringBuilder represents a mutable series of characters in Java. Because the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides a mutable sequence of characters as an alternative to the String Class. StringBuilder and StringBuffer are pretty similar in function since both provide an alternative to String Class by creating a mutable sequence of characters. On the other hand, the StringBuilder class differs from the StringBuffer class in terms of synchronization.

The StringBuilder class has no synchronization guarantee, whereas the StringBuffer class does. As a result, this class is intended to be used as a drop-in replacement for StringBuffer. Especially in situations where a single thread was using the StringBuffer (as is generally the case). It is advised that this class be used instead of StringBuffer whenever possible, as it will be faster in most cases. StringBuilder instances are not safe to use by multiple threads. If this type of synchronization is required, StringBuffer should be used. When compared to StringBuffer, StringBuilder is not thread-safe and has a low speed.

Source: https://www.codeunderscored.com/stringbuilder-in-java-explained-with-examples/

How to use Python Double Slash Previous post How to use Python Double Slash
Stack and Queue in Java with examples Next post Stack and Queue in Java with examples

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.