How to Reverse a string in Java

In this tutorial, we are going discuss different ways to reverse a string in java with examples.

Reversing a string is a task where you change the order of characters in a string so that the last character becomes first, the second-to-last character becomes second and so on.

Examples

Input: Str="String"
Output: Str="gnirtS"
Input: Str="CodeSpeedy"
Output: Str="ydeepSedoC"  

In java, there are many ways to reverse String. But two common ways to reverse string are StringBuilder and using loop to iterate through the string.

Java StringBuilder class is used to create mutable String. So that you can modify the string. It is similar to StringBuffer class, but the difference between this classes is that StringBuilder is not thread-safe.

In Java loop is used to iterate a part of the program repeatedly or several times. There are three types of loops in java.

1.for loop

Java for loop is same as in C language. We can initialize the variable, check the condition and increment/decrement value.

2.while loop

A java while loop allows the code to be executed repeatedly based on the boolean condition.

3.do-while loop

In java, do while loop is similar to while loop with only difference is that it checks the condition after executing the code.

Syntax

StringBuilder s1=new StringBuilder();

Method 1

Loop to Iterate the String Method

Example

public class ReverseString{
public static void main(String[] args){
String original="Code Speedy";
String reversed="";
for(int i=original.length()-1;i>=0;i--){
reversed+=original.charAt(i);
}
System.out.println(reversed);
}
}

Output

Let’s see the output:

ydeepS edoC

Method2

StringBuilder Method

Let’s see how to reverse a string using StringBuilder method

Example

Let’s see the example of StringBuilder Method

public class ReverseString{
public static void main(String[] args){
String original="Code Speedy";
StringBuilder reversed=new StringBuilder(original).reverse();
System.out.println(reversed);
}
}

Output

Let’s see the output of the above code

ydeepS edoC

Both methods will output the reversed string “ydeepS edoC”

In Java, reversing a string can be done efficiently using either StringBuilder or by manually iterating through the string. Using StringBuilder’s ‘reverse()’ method is more efficient for larger strings, as it directly modifies the sequence of the string or character sequence in the string. On the other hand, using a loop is used in certain cases such as when you need more control over the reversing process or when working in environments where StringBuilder is not available. Overall both methods will achieve the same goal of reversing a string.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top