Get in Touch With Us

Submitting the form below will ensure a prompt response from us.

Reversing a string using StringBuilder in Java is simple and efficient because StringBuilder provides a built-in reverse() method that allows you to reverse the string in a single step.

Steps to Reverse a String Using StringBuilder:

Create a StringBuilder Object:

First, create a StringBuilder object and pass the string you want to reverse to it.

StringBuilder sb = new StringBuilder("Hello");

Use the reverse() Method:

Call the reverse() method on the StringBuilder object.

sb.reverse();

Convert Back to String (if needed):

If you need the reversed string as a String object, use the toString() method.

String reversedString = sb.toString(); 
System.out.println(reversedString); // Output: "olleH"

Example Code:

public class ReverseStringExample { 
public static void main(String[] args) { 
StringBuilder sb = new StringBuilder("Java"); 
sb.reverse(); S
ystem.out.println(sb.toString()); // Output: "avaJ" 
} 
}

Important Considerations:

  • StringBuilder is mutable, so it directly modifies the original object without creating new ones, making it more memory-efficient for operations like reversing strings.
  • This method is ideal when you need to reverse a string multiple times or perform other modifications.
About Author

Jayanti Katariya is the CEO of Moon Technolabs, a fast-growing IT solutions provider, with 18+ years of experience in the industry. Passionate about developing creative apps from a young age, he pursued an engineering degree to further this interest. Under his leadership, Moon Technolabs has helped numerous brands establish their online presence and he has also launched an invoicing software that assists businesses to streamline their financial operations.

Related Q&A