×

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

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.