×

How to Reverse a String in Java

How to Reverse a String in Java

There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a given string. Let’s see different ways to the string reversal.

By using StringBuilder


Consider the following program.

FileName: StringReverseExample.java

 public class StringReverseExample
{
// main method
public static void main(String argvs[])
{
    // input string
    StringBuilder str = new StringBuilder("I am not a terrorist.");
    System.out.println("The given string is :");
    System.out.println(str + "\n");
    // invoking the reverse() method
    str.reverse();
    System.out.println("The string after reversal is :");
    System.out.println(str);
}
} 

Output:

 The given string is :
I am not a terrorist.
The string after reversal is :
.tsirorret a ton ma I 

By using StringBuffer


Consider the following program.

FileName: StringReverseExample1.java

 public class StringReverseExample1
{
// main method
public static void main(String argvs[])
{
    // input string
    StringBuffer str = new StringBuffer("I am not a terrorist.");
    System.out.println("The given string is :");
    System.out.println(str + "\n");
    // invoking the reverse() method
    str.reverse();
    System.out.println("The string after reversal is :");
    System.out.println(str);
}
} 

Output:

 The given string is :
I am not a terrorist.
The string after reversal is :
.tsirorret a ton ma I

By using Char Array


Consider the following program.

FileName: StringReverseExample2.java

 // A Java program that shows how to use char array to do the reversal of the given string
class StringReverse
{ 
// method to do the string reversal
public String reverseString(String s)
{ 
    // converting to char array
    char c[] = s.toCharArray();
    String ans="";
    // calculating length of the string s
    int  length = c.length;
    // iterating over the characters of the given string
    for(int j = length - 1; j >= 0; j--)
    { 
        ans += c[j]; 
    } 
    return ans; 
} 
} 
public class StringReverseExample2
{ 
// main method   
public static void main(String argvs[])
{ 
// input string
String str = "I am not a terrorist.";
// creating an object of the StringReverse clas
StringReverse sr = new StringReverse();
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str);
System.out.println("The reverse string is: " + str + "\n");
str = "I am a good person.";
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str);
System.out.println("The reverse string is: " + str + "\n");
} 
}  

Output:

 The given string is: I am not a terrorist.
The reverse string is: .tsirorret a ton ma I
The given string is: I am a good person.
The reverse string is: .nosrep doog a ma I 

Explanation: In the above program, the string is converted into the character array. Then, the character array is traversed from the end to the beginning, i.e., in reverse order to generate the reverse of the given string.

By using the charAt() method

The charAt() has the following syntax.

Syntax:

public char charAt(int index)

FileName: StringReverseExample3.java

 // A Java program that shows how to use the charAt() to do the reversal of the given
// string
class StringReverse
{ 
// method to do the string reversal
public String reverseString(String s)
{
    String ans=""; 
    // calculating length of the string s
    int  length = s.length();
    // iterating over the characters of the given string
    for(int j = length - 1; j >= 0; j--)
    { 
        ans += s.charAt(j); 
    } 
    return ans; 
} 
} 
public class StringReverseExample3
{ 
// main method   
public static void main(String argvs[])
{ 
// input string
String str = "I am not a terrorist.";
// creating an object of the StringReverse clas
StringReverse sr = new StringReverse();
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str);
System.out.println("The reverse string is: " + str + "\n");
str = "I am a good person.";
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str);
System.out.println("The reverse string is: " + str + "\n");
} 
}  

Output:

 The given string is: I am not a terrorist.
The reverse string is: .tsirorret a ton ma I
The given string is: I am a good person.
The reverse string is: .nosrep doog a ma I 

Explanation: The charAt(j) method takes returns the character present at the index j. Since the for-loop is iterating from the last index of the string to the first index. Therefore, at first, the character present at the last index gets copied. Then the character present at the penultimate index and so on. After the end of the for-loop, the string ans stores the string, which is the reverse of the string that is passed as the parameter of the method reverseString().

By using stack

Stack can also be used for the reversal of a given string. The following program illustrates the same.

FileName: StringReverseExample4.java

 // A Java program that shows how to use the stack to do the reversal of the given string
import java.util.Stack;
class StringReverse
{ 
// method to do the string reversal
public String reverseString(String s)
{
    String ans=""; 
    // calculating length of the string s
    int  length = s.length();
    // creating a stack
    Stack<Character> stk = new Stack();
    // iterating over the characters of the given string
    for(int j = 0; j < length; j++)
    { 
        stk.push(s.charAt(j)); 
    }
    // iterate till the stack becomes empty
    while(!stk.empty())
    {
        // taking the top element from
        // the stack and concatenating it to
        // the string ans
        ans += stk.peek();
        // removing the peek element from the stack
        stk.pop();
    }
    // return the result
    return ans;
} 
} 
public class StringReverseExample4
{ 
// main method   
public static void main(String argvs[])
{ 
// input string
String str = "I am not a terrorist.";
// creating an object of the StringReverse clas
StringReverse sr = new StringReverse();
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str);
System.out.println("The reverse string is: " + str + "\n");
str = "I am a good person.";
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str);
System.out.println("The reverse string is: " + str + "\n");
} 
} 

Output:

 The given string is: I am not a terrorist.
The reverse string is: .tsirorret a ton ma I
The given string is: I am a good person.
The reverse string is: .nosrep doog a ma I 

Explanation: The LIFO (Last In First Out) property of the stack comes in handy to do the reversal of the given string. The for-loop of the reverseString() method puts the characters, one by one, starting from the first index to the last index. Thus, when a character is popped from the stack, the last character comes out first, then the second last character, and so on. Thus, after the end of the while-loop, the string contained in the ans, is the reverse of the string that is passed as the parameter of the method reverseString().

By using recursion

The recursive approach can also be used to do the reverse of the given string. The following program illustrates the same.

FileName: StringReverseExample5.java

 // A Java program that shows how to use recursion to do the reversal of the given string
class StringReverse
{ 
// method to do the string reversal using recursion
public String reverseString(String s, int i, int size)
{
    // handling the base case
    if(i >= size)
    {
        return "";
    }
    String ans=""; 
    // recursively calling the method reverseString()
    ans += reverseString(s, i + 1, size) + s.charAt(i);
    // return the result
    return ans;
} 
} 
public class StringReverseExample5
{ 
// main method   
public static void main(String argvs[])
{ 
// input string
String str = "I am not a terrorist.";
// calculating the size of the string
int size = str.length();
// creating an object of the StringReverse clas
StringReverse sr = new StringReverse();
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str, 0, size);
System.out.println("The reverse string is: " + str + "\n");
str = "I am a good person.";
// calculating the size of the string
size = str.length();
System.out.println("The given string is: " + str);
// invoking the reverseString() method
str = sr.reverseString(str, 0, size);
System.out.println("The reverse string is: " + str + "\n");
} 
} 

Output:

 The given string is: I am not a terrorist.
The reverse string is: .tsirorret a ton ma I
The given string is: I am a good person.
The reverse string is: .nosrep doog a ma I 

Explanation: Using recursion, first, we are moving to the end of the given string. Then, the concatenation work starts using the + operator with the help of the method charAt(). Thus, at first, the last character, then the second last character gets concatenated, and eventually, we get a reverse of the given string.


Related Topics

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.