Java Program to Reverse a String.

reverse string in Java

In this article, we will understand multiple approaches to reverse a string in Java Programming. 


We can reverse a string using the below approaches:

  • Reverse a string using a loop.
  • Reverse a string using the StringBuilder class.
  • Reverse a string using Recursion.

Let,s discuss each of them one by one,


Reverse a string using a loop.

One way to reverse a string is to use a loop and iterate through the characters of the string in reverse order. We can then append each character to a new string to create the reversed string.

Java Code Implementation:

// Java code to reverse string using loop
class HelloWorld {
    public static void main(String[] args) {
        String str = "Algolesson";
        System.out.println(reverseString(str));
    }
    public static String reverseString(String str) {
       String reversed = "";
       for (int i = str.length() - 1; i >= 0; i--) {
          reversed += str.charAt(i);
       }
       return reversed;
   }
}
Output:
nosseloglA
  • Time Complexity: O(n)
  • Space Complexity: O(n)


Reverse a String using StringBuilder Class.

Java provides a StringBuilder class that has a reverse() method to reverse a string. We can create a StringBuilder object and then call the reverse() method to get the reversed string. This is the most efficient approach to reversing a string.

Java Code Implementation:
// Java code to reverse string using StringBuilder class
class HelloWorld {
    public static void main(String[] args) {
        String str = "Algolesson";
        System.out.println(reverseString(str));
    }
    public static String reverseString(String str) {
        StringBuilder sb = new StringBuilder(str);
        sb.reverse();
        return sb.toString();
    }
}
Output:
nosseloglA
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Reverse a String using Recursion.

This approach is to use recursion to reverse a string. We can recursively swap the first and last characters of the string until we reach the middle of the string. This is the least efficient approach and can cause a stack overflow if the string is very long. 

Java Code Implementation:
// Java code to reverse string using Recursion
class HelloWorld {
    public static void main(String[] args) {
        String str = "Algolesson";
        System.out.println(reverseString(str));
    }
    public static String reverseString(String str) {
        if (str.isEmpty()) {
           return str;
        } else {
           return reverseString(str.substring(1)) + str.charAt(0);
        }
    }
}
Output:
nosseloglA
  • Time Complexity: O(n)
  • Space Complexity: O(n)

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS