Java .toString()

StevenSwiniarski's avatar
Published Aug 22, 2022
Contribute to Docs

The .toString() method returns a String representation of the character sequence currently in a given StringBuilder.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

myStringBuilder.toString();

The .toString() method takes no arguments.

Example

The following example creates a StringBuilder with a specified String, manipulates it, then uses .toString() to print the results:

import java.util.*;
public class Example {
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Hello World!");
String s1 = str.toString();
System.out.println(s1);
str.reverse();
String s2 = str.toString();
System.out.println(s2);
}
}

This produces the following output:

Hello World!
!dlroW olleH

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours