StringBuilder Basics
Part of the Logic & Flow section of Coddy's Java journey. Lesson 44 of 59.
StringBuilder is used to create mutable (modifiable) strings. It's more efficient than regular String concatenation when you need to modify strings multiple times.
Create a StringBuilder with initial text:
StringBuilder sb = new StringBuilder("Hello");Add more text using append():
sb.append(" World");After executing the above code, sb contains:
Hello World
Let's use insert() to add text at a specific position:
StringBuilder sb = new StringBuilder("Java");
sb.append(" is"); // adds at end
sb.insert(0, "Hey "); // adds at position 0 (start)After executing the above code, sb contains:
Hey Java is
Converting StringBuilder to String:
When you need to return or store the result as a String, use toString():
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
String result = sb.toString(); // Converts to String
System.out.println(result); // Prints: Hello WorldWhy use toString()? Methods that return String type cannot return a StringBuilder directly - you must convert it first using toString().
Challenge
EasyCreate a method named buildPhrase that takes three arguments:
- A String (
start) for the beginning of the phrase - A String (
middle) for the middle part - A String (
end) for the ending
The method should:
- Create a StringBuilder with the start string
- Add a space and the middle string
- Add a space and the end string
- Add an exclamation mark at the end
- Return the final string
Return messages should be:
- If any input is null: return "Invalid input"
- For successful operation: return the built phrase
Try it yourself
import java.util.Scanner;
public class Main {
public static String buildPhrase(String start, String middle, String end) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String start = scanner.nextLine();
String middle = scanner.nextLine();
String end = scanner.nextLine();
if (start.equals("null")) start = null;
if (middle.equals("null")) middle = null;
if (end.equals("null")) end = null;
System.out.println(buildPhrase(start, middle, end));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap5HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceSubsets and SupersetsIterating Over Sets8Advanced String Operations
StringBuilder BasicsStringBuffer IntroductionRegular Expressions BasicsPattern Matching with RegexString TokenizerAdvanced String FormattingPractice on your own: Online Java compiler