Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a method named modifyText that takes three arguments:

  1. A String (text) to modify
  2. A String (target) to find
  3. A String (replacement) to replace target with

The method should:

  1. Create a StringBuffer with the input text
  2. Replace the first occurrence of target with replacement
  3. Add an exclamation mark at the end
  4. 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 beginning

Replace text using replace():

sb.replace(0, 2, "Hey");  // replaces characters from index 0 to 2

Try 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));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow