March 17, 2024

How to Reverse a String in Java

In this post we’ll see how to reverse a string in Java. Though StringBuffer and StringBuilder classes in Java have a reverse() method that can be used to reverse a String but you may be asked to write your own logic to reverse a String. In that case too you can do it by iteration or by recursion. All the three solutions are given here.

1. Using StringBuilder/StringBuffer class

public class ReverseString {
  public static void main(String[] args) {
    StringReverse("String reverse program in knpcode");
  }

  // Method using StringBulider class reverse method
  private static void StringReverse(String str){
    StringBuilder sb = new StringBuilder(str);
    System.out.println("Reversed String- " + sb.reverse().toString());
  }
}
Output
Reversed String- edocpnk ni margorp esrever gnirtS

2. Using iterative method to reverse a String

If you are using iterative method to reverse a string in Java then you need to loop the String starting from the end and keep adding each character to a String.

public class ReverseString {
  public static void main(String[] args) {
    StringReverse("String reverse program in knpcode");
  }

  // Method using StringBulider class reverse method
  private static void StringReverse(String str){
    StringBuilder sb = new StringBuilder();
    // read string backward
    for(int i = str.length() - 1; i >= 0; i--){
      sb.append(str.charAt(i));
    }
    System.out.println("Reversed String- " + sb.toString());
  }
}
Output
Reversed String- edocpnk ni margorp esrever gnirtS

3. Using recursive method to reverse a String

public class ReverseString {
  public static void main(String[] args) {
    String reversedString = StringReverse("test line");
    System.out.println("Reversed String- " + reversedString);
  }

  // Method using StringBulider class reverse method
  private static String StringReverse(String str){
    //base case
    if((str == null) || (str.length() <= 1)){
        return str;
    }
    // Take the substring from index 1 till last
    // append the char at index 0 at the last
    return StringReverse(str.substring(1)) + str.charAt(0);
  }
}
Output
Reversed String- enil tset

That's all for the topic How to Reverse a String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment