Menu
Coddy logo textTech

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 World

Why use toString()? Methods that return String type cannot return a StringBuilder directly - you must convert it first using toString().

challenge icon

Challenge

Easy

Create a method named buildPhrase that takes three arguments:

  1. A String (start) for the beginning of the phrase
  2. A String (middle) for the middle part
  3. A String (end) for the ending

The method should:

  1. Create a StringBuilder with the start string
  2. Add a space and the middle string
  3. Add a space and the end string
  4. Add an exclamation mark at the end
  5. 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));
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online Java compiler