Table of contents
1.
Introduction
2.
Approach
3.
Using user-defined method
3.1.
Method
3.2.
Complexity
4.
Using reverse() method of StringBuilder Class
4.1.
Method
4.2.
Complexity
5.
Without using method
5.1.
Method
5.2.
Complexity
6.
Using ArrayList object
6.1.
Method
6.2.
Complexity
7.
FAQs
8.
Key Takeaways
Last Updated: Sep 29, 2024

Reverse a String in Java

Author Nagendra
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

One of the most widely used programming languages on the planet is Java. Learning Java reinforces essential computer science principles while also providing access to a wide range of professional options.

Reverse a string in Java

In this blog, we are going to learn different methods of reversing a string in Java. 
Before going forward, some facts about the String and StringBuilder classes in Java are as follows:

  • The index of strings starts from 0.
  • String objects are immutable.
  • The String class in Java does not have a reverse() method; however, the StringBuilder class does.

Approach

  1. Using user-defined method
  2. Using a reverse() method of StringBuilder Class
  3. Without using a method.
  4. Using ArrayList object

Using user-defined method

Method

  • Define a Method with the original String as parameter and return value.
  • Create a new String inside it.
  • Concatenate the String with the reverse order of the original String.
  • Return the new String from the Method.
  • Call the function in the main() Method

The following program explains the use of a predefined method in order to reverse a string.

public class Ninja {
public static String reverse(String s) //Creating user-defined function named reverse
{
     String reverse_string="";    //Creating a new string
     for(int i=s.length()-1; i>=0;--i)  //traversing the loop backward
     {
            reverse_string+=s.charAt(i);
     }
     return reverse_string;
}
public static void main(String ar[])
{
     String str="Coding Ninjas";
        System.out.println(reverse(str)); //Calling the reverse function
    
}
}
You can also try this code with Online Java Compiler
Run Code

Output :

sajniN gnidoC
You can also try this code with Online Java Compiler
Run Code

Complexity

Time complexity :O(n)
Space Complexity : O(1)
Must Read  C Program to Reverse a Number

Using reverse() method of StringBuilder Class

Method

The reverse() method is a predefined method of the StringBuilder class in java.Using the predefined methods makes the program quite simple and understandable.
The following program illustrates the use of StringBuilder class in order to reverse a string:

public class Ninja {
  public static void main(String args[]){
      String str = "Coding Ninjas";
      StringBuilder sb = new StringBuilder(str);
      sb.reverse();  //Using the reverse function of Stringbuilder class
      System.out.println(sb);
  }
}
You can also try this code with Online Java Compiler
Run Code

Output :

sajniN gnidoC
You can also try this code with Online Java Compiler
Run Code

Complexity

Time complexity :O(n)
Space Complexity : O(1)

Must Read Array of Objects in Java

Without using method

Method

  • Create a new String
  • Concatenate the String with the reverse order of the original String.
  • Print the new String generated.

The following program illustrates the reverse of string without using method :

public class Ninja {
public static void main(String ar[])
	{
     String str="Coding Ninjas";
       String reverse_string=""; //Creating a new string
     for(int i=str.length()-1; i>=0;--i) //traversing the loop backward
     {
            reverse_string+=str.charAt(i);
     }
   
        System.out.println(reverse_string);
    
	}
}
You can also try this code with Online Java Compiler
Run Code

Output :

sajniN gnidoC
You can also try this code with Online Java Compiler
Run Code

Complexity

Time complexity :O(n)
Space Complexity : O(1)


Check out this problem - Longest String Chain, and Duck Number in Java.

Also check out Addition of Two Numbers in Java here.

Using ArrayList object

Method

  • Copy the String to an ArrayList object
  • Use the predefined method to reverse the String
  • Create a ListIterator to iterate over the Array List
  • Print the ArrayList using the ListIterator.

The following program illustrates the reverse of string using ArrayList object :

import java.util.*;
public class Ninja {
    public static void main(String ar[])
    {
        String str = "Coding Ninjas";   	//Given String
        char[] arr = str.toCharArray(); 	//Changing the String to Character Array
        List<Character> arr_list = new ArrayList<>(); 	//Creating array list object
        for (char c : arr)
            arr_list.add(c);    	//adding each character to the list
        Collections.reverse(arr_list);  	//predefined method to reverse list
        ListIterator itr = arr_list.listIterator(); 	//creating iterator
        while (itr.hasNext())
            System.out.print(itr.next());   	//printing the reversed elements using iterator
    } 
}
You can also try this code with Online Java Compiler
Run Code

Output :

sajniN gnidoC
You can also try this code with Online Java Compiler
Run Code

Complexity

Time complexity :O(n)
Space Complexity : O(1)


You can easily run this code yourself with java online compiler.

You can also checkout Java List Iterator here.

FAQs

  1. Are Strings in Java mutable?
    No, Strings in Java are immutable.
     
  2. What is StringBuilder ? 
    StringBuilder is a Class in Java that allows you to generate a mutable, or changeable, sequence of characters.
     
  3. What is the use of the reverse() method of StringBuilder Class?
    The reverse() method of StringBuilder Class is used to reverse a string.
     
  4. What is the Average Time Complexity of reversing a string?
    The Time Complexity of reversing a string is O(n).

Key Takeaways

In this article, we have extensively discussed the reverse of strings and their implementation in Java. The article explains the different approaches used to reverse a string in Java. The use of the user-defined method, reverse() method of StringBuilder Class, and without using function are explained . There are many more approaches, but these are the most efficient in terms of time and space.

Related articles:

We hope that this blog has helped you enhance your knowledge regarding the reverse of string and if you would like to learn more, check out our articles on Java. Do upvote our blog to help other ninjas grow. 
Happy Coding!

Live masterclass