Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Challenge Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Optional Java Advanced Sorting

Java Projects

Java Projects

Java Cert

Java Certificate

Java How To's

Java How Tos

Java Reference

Java Reference Java Keywords Java String Methods Java StringBuilder Methods Java Math Methods Java Output Methods Java Arrays Methods Java ArrayList Methods Java LinkedList Methods Java HashMap Methods Java Scanner Methods Java File Methods Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter Java Iterator Methods Java Collections Methods Java System Methods Java Errors & Exceptions

Java Examples

Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A


Java StringBuilder


Share

Java StringBuilder

In the String Concatenation chapter, you learned to join strings with the + operator.

But a String cannot be changed after it is created. When you add text to a string, Java does not change the old string. It creates a new string every time.

A StringBuilder is a string that can be changed. You can add, insert, replace, delete and reverse text, and Java keeps changing the same text. Think of it like a document that you keep editing, instead of writing a new copy for every change.

Example

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);

Try it Yourself »

Example explained

  • new StringBuilder("Hello") creates a StringBuilder with the text "Hello".
  • sb.append(" World") adds " World" to the end of the text.
  • System.out.println(sb) prints the text: Hello World

Note: The new keyword creates the StringBuilder. You will learn more about new in the Classes and Objects chapter.


Add Text with append()

The append() method adds text to the end. You can call it as many times as you like, and it also works with numbers.

Empty parentheses, new StringBuilder(), create an empty StringBuilder:

Example

StringBuilder sb = new StringBuilder();
sb.append("Liam");
sb.append(" has ");
sb.append(3);
sb.append(" apples");
System.out.println(sb);

Try it Yourself »

Tip: You can also write several append() calls on one line: sb.append("Liam").append(" has ").append(3);



Insert, Replace and Delete

A StringBuilder can also change text in the middle. These methods use positions, just like charAt(). Remember that Java counts positions from 0:

  • insert(position, text) inserts text at a position
  • replace(start, end, text) replaces the characters from start to end
  • delete(start, end) removes the characters from start to end

Example

StringBuilder sb = new StringBuilder("I like cats");
sb.insert(7, "black ");      // I like black cats
sb.replace(13, 17, "dogs");  // I like black dogs
sb.delete(7, 13);            // I like dogs
System.out.println(sb);

Try it Yourself »

Note: The end position is not included. delete(7, 13) removes the characters at positions 7 to 12, which is the text "black ".


Reverse Text

The reverse() method reverses the order of the characters:

Example

StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);  // olleH

Try it Yourself »

This is the quickest way to reverse a string in Java. See also How To Reverse a String.


Convert to a String

Use toString() to turn a StringBuilder into a normal String. You need this when you want to use String methods, like toUpperCase(), or store the text in a String variable:

Example

StringBuilder sb = new StringBuilder("hello");
sb.append(" world");
String text = sb.toString();
System.out.println(text.toUpperCase());  // HELLO WORLD

Try it Yourself »


String vs. StringBuilder

Use a String for text that does not change, like a name or a message.

Use a StringBuilder when you change the text many times, for example when you add text inside a loop (you will learn about loops in a later chapter). It is faster, because Java does not have to create a new string for every change.


Complete StringBuilder Reference

For a complete reference of StringBuilder methods, go to our Java StringBuilder Methods Reference.

The reference contains descriptions and examples of all StringBuilder methods.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.