We may not have the course you’re looking for. If you enquire or give us a call on 01344203999 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Strings in Java, once declared, are immutable, and changes like appending, deleting and replacing cannot be made to the object that has been declared. StringBuilder in Java allows you to make changes to strings in real-time.
StringBuilder class is a part of java.lang package and was introduced in Java 5 as a more efficient alternative to the older StringBuffer class. This blog will discuss StringBuilder in Java, its important Constructors and methods, and an example of its functionality. Read this blog to learn further!
Table of Contents
1) What is StringBuilder in Java?
2) Important Constructors of StringBuilder in Java
3) Important methods of StringBuilder in Java
4) Java StringBuilder Example
5) Conclusion
What is StringBuilder in Java?
StringBuilder in Java allows you to create a mutable sequence of characters. It is similar to String but allows efficient modification of its contents without creating a new object. In other words, a StringBuilder can dynamically build and modify strings as necessary.
When a new StringBuilder object is created, it can initially hold a certain number of characters. This capacity can be increased as needed, as more characters can be added to the sequence. The size of the StringBuilder is the number of characters currently in the sequence, while the capacity is the maximum number of characters it can hold without needing to resize.
StringBuilder can also be used with StringBuffer, a thread-safe version of StringBuilder. The main difference between the two is that StringBuilder is not thread-safe, meaning multiple threads cannot access it simultaneously. At the same time, StringBuffer can be used by multiple threads simultaneously.
StringBuilder provides a convenient way to efficiently build and modify strings in Java, making it a useful tool for many programming tasks.
Important Constructors of StringBuilder in Java
The important Constructors of StringBuilder in Java are as follows:
The important Constructors of StringBuilder in Java are as follows:
1) StringBuilder(): This Constructor allows you to create an empty StringBuilder object with an initial capacity of 16 characters.
2) StringBuilder(int capacity): This Constructor allows you to create an empty StringBuilder object with the specified initial capacity.
3) StringBuilder(CharSequence seq): This Constructor allows you to create a StringBuilder object initialised with the contents of the specified CharSequence, such as a String or a StringBuilder.
4) StringBuilder(String str): This Constructor allows you to create a StringBuilder object initialised with the contents of the specified string.
All four Constructors create a StringBuilder object that can manipulate strings dynamically. Once you have a StringBuilder object, you can use various methods to manipulate its string. Unlike the immutable String class, the StringBuilder class is mutable, which means you can modify its contents without creating a new object.
Boost your knowledge of Java by learning more about Constructors in Java. Sign up for the Java Programming course now!
Important methods of StringBuilder in Java
Here are some important methods of StringBuilder in Java:
1) append(): This method is used to append a string or character to the end of a StringBuilder object.
2) insert(): This method is used to insert a string or character at a specified position in a StringBuilder object.
3) delete(): This method is used to delete a string or character or a specified portion of a StringBuilder object.
4) replace(): This method is used to replace a string or character or a specified portion of a StringBuilder object with a new string.
5) substring(): This method is used to obtain a substring of the StringBuilder object.
6) length(): This method is used to obtain the length of the entire StringBuilder object or a selected portion of it.
7) capacity(): This method is used to understand the current capacity of the StringBuilder object.
8) ensureCapacity(): This method is used to ensure that the StringBuilder object has a minimum capacity.
9) trimToSize(): This method is used to trim the capacity of the StringBuilder object to its current length.
10) toString(): This method is used to convert the entire StringBuilder object or a portion of it to a string.
11) reverse(): This method is used to reverse the characters in the entire StringBuilder object or a selection portion of it.
12) charAt(): This method is used to get the character at a specified index in the StringBuilder object.
13) setCharAt(): This method is used to set the character at a specified index in the StringBuilder object.
Refer Our Java Questions and Answers to get through the Interviews with ease.
Java StringBuilder Example
import java.util.Scanner;
public class StringBuilderExample
{
public static void main(String[] args) ;
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
StringBuilder sb = new StringBuilder();
// Loop through each character in the sentence
for (int i = 0; i < sentence.length(); i++)
{
char c = sentence.charAt(i);
// If the character is a space, add it to the string builder if (c == ' ')
{
sb.append(c);
}
else
{
// Otherwise, check if the character is a letter
if (Character.isLetter(c))
{
// If it's the first letter in a word, capitalize it
if (i == 0 || sentence.charAt(i - 1) == ' ')
{
sb.append(Character.toUpperCase(c));
}
else
{
// Otherwise, add it in lowercase sb.append(Character.toLowerCase(c))
}
}
else
{
// If the character is not a letter, add it as-is sb.append(c);
}
}
}
System.out.println("Formatted sentence: " + sb.toString());
}
}
This program formats a user-input sentence by capitalising the first letter of each word and converting all other letters to lowercase. It also preserves any punctuation and spaces.
It accomplishes this by looping through each character in the input string, checking if it's a letter or a space, and then appending the appropriate character to the StringBuilder. The resulting string is then printed to the console.
Conclusion
Introduced as a replacement for the more volatile StringBuffer, StringBuilder provides a more convenient and faster way to edit string objects. StringBuilder is also non-synchronous, meaning multiple threads can access the StringBuilder object simultaneously.
In conclusion, StringBuilder in Java is a fundamental aspect that programmers must know and understand fully.
Sign up for Objected-Oriented Fundamentals Training in Virtual to build your fundamentals on programming languages now!
Frequently Asked Questions
The StringBuilder class in Java is a mutable sequence of characters that allows you to modify the contents of a string. It is faster than StringBuffer and not thread-safe.
Here are some of the common methods of the StringBuilder class:
1) append(): This method appends the string representation of any type of argument to the sequence.
2) insert(): This method inserts the string representation of any type of argument at a specified position in the sequence.
3) delete(): This method removes the characters in a substring of the sequence.
4) reverse(): This method reverses the order of the characters in the sequence.
5) toString(): This method returns a string representing the data in the sequence.
It reduces memory usage and improves the performance of string operations, as it does not create a new object with every update. Besides, it provides an API compatible with StringBuffer but with no guarantee of synchronisation, making it suitable for single-threaded environments. Moreover, it offers various methods to manipulate strings, such as appending, inserting, deleting, and reversing.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various Java Courses, including Java Programming Course, JavaScript for Beginners and Java Engineer Training. These courses cater to different skill levels, providing comprehensive insights into Latest Java Technologies Trends.
Our Java blogs cover a range of topics related to PRINCE2, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Project Management skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
Upcoming Programming & DevOps Resources Batches & Dates
Date
Mon 20th Jan 2025
Mon 3rd Mar 2025
Mon 12th May 2025
Mon 14th Jul 2025
Mon 22nd Sep 2025
Mon 17th Nov 2025