How to Reverse String in Java with Program

In this tutorial, we will learn how to reverse a string by word or character in Java with example program.

A string is a sequence of characters that is considered as an object in Java. In Java, string is an immutable class.

That means, once a string object has been constructed, it is not possible to change its contents. If we attempt to change its contents, a new string object will be constructed in the memory.

So, when we will try to reverse a string by word or character at a time, we will produce a new string object, with contents reversed.

In Java, there are several operations that we can perform on the String object. String reverse is one of the most widely performing operations on a string.

In this tutorial, we will learn the various approaches to reverse a String in Java.

How many ways to Reverse String in Java


In Java, there are various ways or approaches by which we can reverse a string. They are as follows:

  • Reverse a string using charAt() method without using reverse() methed
  • Reverse a string using StringBuffer / StringBuilder approach
  • String reverse using Reverse Iterative Approach
  • String reverse using Recursion
  • Reverse a string using swapping of variables.
  • Reverse a string using reverse() method of Collections class
  • Reversing a string by word.

So, let’s start with the first approach and understands how to reverse a string in Java using charAt() method.

Reverse a String using charAt() without using Reverse Method


String class provides a charAt() method that returns the character at the specified index from the string. We are using this CharAt() method in order to extract the characters from the input string.

Then, we will append them in reverse order to reverse the string. The length() method of String class returns the length of string (i.e., number of characters in the string).


This is one of the simple approaches to reverse a string in Java. Look at the following source code given below.

Program code 1:

package stringProgram;
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) 
{
// Create a empty string.	
     String reverse = "";
// Accept string from user using scanner class.    
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter a string to reverse:");
     String original = sc.nextLine();

// Find the length of entered string using length() method of String class.	
     int length = original.length();
     for(int i = length - 1; i >= 0; i--)
	reverse = reverse + original.charAt(i);
	System.out.println("Reversed string: "+reverse);
   }
}
Output:
      Enter a string to reverse:
      Hello Scientech Easy
      Reversed string: ysaE hcetneicS olleH

Hope that you will have understood this simple approach to reverse a given string in Java. Let’s move further and understand how to reverse a string using StringBuffer or StringBuilder class.

Reversing a String using StringBuffer / StringBuilder class


StringBuffer/StringBuilder class is an alternative to a String class. It is more flexible than a string. We can reverse a string in StringBuffer or StringBuilder without creating a new object. That is, we can easily add, insert, etc. new contents into a string buffer or string builder.

StringBuffer class is similar to StringBuilder except that methods of StringBuffer class are synchronized. Whereas, methods of StringBuilder class are not synchronized.


StringBuffer and StringBuilder classes provide an inbuilt reverse() method which reverse the characters in the buffer or builder. This method replaces the sequence of characters in the reverse order.

The code to reverse a string using a built-in method of the StringBuilder class is given below.

Program code 2:

package stringProgram;
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) 
{   
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter a string to reverse:");
   String original = sc.nextLine();

// Create a StringBuilder object and pass the original variable as parameter.	
     StringBuilder sb = new StringBuilder(original);
      sb.reverse(); // calling reverse method of StringBilder class.
    System.out.println("Reversed string: " +sb);
	}
}
Output:
     Enter a string to reverse:
     Java Technology
     Reversed string: ygolonhceT avaJ

In this program, we have used reverse() method of StringBuilder that is not synchronized, and faster than StringBuffer.

Alternatively, we can also use reverse() method of StringBuffer class that is synchronized. Look at the below code to reverse string in java using string buffer.

Program code 3:

package stringProgram;
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) 
{   
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter a string to reverse:");
   String original = sc.nextLine();

// Create a StringBuffer object and pass the original variable as parameter.	
     StringBuffer sb = new StringBuffer(original);
      sb.reverse(); // calling reverse method of StringBuffer class.
     System.out.println("Reversed string: " +sb);
  }
}
Output:
      Enter a string to reverse:
      Programming
      Reversed string: gnimmargorP

Reverse a String using Reverse Iteration


In this approach, we will convert string into characters one by one using toCharArray() method. After that, we will just iterate the given characters array in the reverse order. Look at the following source code to understand this technique.

Program code 4:

package stringProgram;
public class ReverseString 
{  
// Create a method to reverse a string in Java. 
    public static String reverseString(String str)
    {
 // Converting string into a character array using toCharArray() method.
	char[] c = str.toCharArray();
	String reverse = "";
 // Using for loop to reverse a string
	for(int i = c.length-1; i >= 0; i--) {
	   reverse += c[i];
	 }
	 return reverse;
   }
 public static void main(String[] args) 
 {
   System.out.println(reverseString("Hello"));
   System.out.println(reverseString("Welcome to Scientech Easy")); 
 }
}
Output:
      olleH
      ysaE hcetneicS ot emocleW

String Reverse using Recursion


Recursion is nothing but a method or algorithm that calls itself one or more times with different arguments. In this approach, we will create a method which reverses string by invoking itself recursively.

Let’s create a program in which we will reverse a string using recursion.

Program code 5:

package stringProgram;
import java.util.Scanner;
public class StringRecursion 
{  
 public static String reverse(String str) 
 {
    int len = str.length();	 
    if(len == 0)
     return " ";
     return str.charAt(len - 1) + reverse(str.substring(0, len - 1));
 }
 public static void main(String[] args) 
 {
   StringRecursion sr = new StringRecursion();
   Scanner sc = new Scanner(System.in);
   System.out.print("Enter a string: ");
   String s = sc.nextLine();
   System.out.println("Reversed string: "+reverse(s)); 
 }
}
Output:
       Enter a string: Hello
       Reversed string: olleH 

Reversing String using Swapping of Variables


Let’s create a Java program to reverse a string using swapping of variables.

Program code 6:

package stringProgram;
public class StringReverse 
{  
 public static void main(String[] args) 
 {
   String s = "Scientech Easy";
   char[ ] temp = s.toCharArray();
   int i, j = 0;
    j = temp.length - 1;
  for (i = 0; i < j; i++, j--) 
  {
// Swapping values of i and j.
     char t = temp[i];
     temp[i] = temp[j];
     temp[j] = t;
  }
 for (char c : temp)
   System.out.print(c);
   System.out.println();
 }
}
Output:
      ysaE hcetneicS

Reversing String using reverse() method of Collections class


Collections class also provides reverse() method to reverse a string in Java. First, we will convert the input string into the character array by using toCharArray() of String class.

Then, we will create an object of ArrayList and add characters of the array into the ArrayList object. After adding, we will call reverse() method of Collections class and then iterate the array list using Iterator.

The iterator() method of Iterator helps to iterate over the reversed list and display it one by one to the output screen. Let’s create a program based on it.

Program code 7:

package stringProgram;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class StringReverse
{
  public static void main(String[] args)
  {
    String s = "Scientech Easy";
    char[ ] ch = s.toCharArray();
    List<Character> list = new ArrayList<>();

    for (char c : ch)
     list.add(c);
    Collections.reverse(list); // calling reverse() method of Collections class.

    Iterator<Character> li = list.iterator();
    while (li.hasNext())
    System.out.print(li.next());
  }
}
Output:
    ysaE hcetneicS

How to Reverse a String by Word in Java


Let’s create a program in which we will reverse a string by word, not by character, in Java.

Program code 8:

package stringProgram;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
public class StringReverse
{
  public static void main(String[] args)
  {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your string: ");
    String str = sc.nextLine();

    Stack<object> st = new Stack<object>();
    StringTokenizer sTok = new StringTokenizer(str);
    while(sTok.hasMoreTokens())
    {
      st.push(sTok.nextElement());
     }
   StringBuffer sb = new StringBuffer();
   while(!st.empty())
   {
      sb.append(st.pop());
      sb.append(" ");
    }
   System.out.println("Reversed string: " +sb);
   }
}
Output:
      Enter your string: 
      Reverse this string
      Reversed string: string this Reverse 

As you can observe in the program, reversing a string by word is more complicated than reversing a string by character. This is because there is in-built support for reversing a string by character, but there is no in-built support for reversing a string by word.

To accomplish this job, we make the use of Stack and StringTokenizer classes. With the help of StringTokenizer class, we parse each word out of the string and push it onto the stack.

After processed the entire string, we iterate via a stack, popping each word off and appending to a StringBuffer that holds the reversed string. A stack works on the principle of LIFO (last in, first out) that makes the reverse successful.


In this tutorial, you learned how to reverse a string in Java by character and word. Hope that you will have understood the basic concepts of reversing a string by character and word.

Reversing a string in Java is the most important topic and asked by interviewer in company from fresher and experienced.
Thanks for reading!!!
Next ⇒ String Palindrome in Java⇐ Prev Next ⇒