StringBuffer Introduction
Part of the Logic & Flow section of Coddy's Java journey — lesson 45 of 59.
StringBuffer is similar to StringBuilder but is thread-safe (safe for multiple operations at the same time). It's used to create mutable (modifiable) strings.
Create a StringBuffer with initial text:
StringBuffer sb = new StringBuffer("Hello");Add more text using append():
sb.append(" World");After executing the above code, sb contains:
Hello World
Modify text using insert() and replace():
StringBuffer sb = new StringBuffer("Java");
sb.insert(0, "Hi "); // adds at beginning
sb.replace(0, 2, "Hey"); // replaces "Hi" with "Hey"After executing the above code, sb contains:
Hey Java
Challenge
EasyCreate a method named modifyText that takes three arguments:
- A String (
text) to modify - A String (
target) to find - A String (
replacement) to replace target with
The method should:
- Create a StringBuffer with the input text
- Replace the first occurrence of target with replacement
- Add an exclamation mark at the end
- Return the final string
Return messages should be:
- If any input is null: return "Invalid input"
- If target not found: return original text with exclamation mark
- For successful operation: return the modified text
Cheat sheet
StringBuffer is thread-safe and used to create mutable strings.
Create a StringBuffer with initial text:
StringBuffer sb = new StringBuffer("Hello");Add text using append():
sb.append(" World");Insert text at a specific position:
sb.insert(0, "Hi "); // adds at beginningReplace text using replace():
sb.replace(0, 2, "Hey"); // replaces characters from index 0 to 2Try it yourself
import java.util.Scanner;
public class Main {
public static String modifyText(String text, String target, String replacement) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String target = scanner.nextLine();
String replacement = scanner.nextLine();
if (text.equals("null")) text = null;
if (target.equals("null")) target = null;
if (replacement.equals("null")) replacement = null;
System.out.println(modifyText(text, target, replacement));
}
}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 Formatting