Today we are going to understand several best ways to reverse a string in Java :
1.Reverse A String In Java Using String Builder :
package com.crtr4u; public class StringReverse { public static void main(String[] args) { System.out.println(reverseString("abcd")); } // Using String Builder public static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); sb.reverse(); return sb.toString(); } }
2.Using Array Reverse A String In Java:
package com.crtr4u; public class StringReverse { public static void main(String[] args) { System.out.println(reverseStringUsingArray("abcd")); } public static String reverseStringUsingArray(String str) { char[] chars = str.toCharArray(); String rev = ""; for (int i = chars.length - 1; i >= 0; i--) { rev += chars[i]; } return rev; } }
3.Reverse A String In Java Using Recursion:
package com.crtr4u; public class StringReverse { public static void main(String[] args) { System.out.println(reverseStringUsingRecursion("abcd")); } public static String reverseStringUsingRecursion(String str) { if (str.isEmpty()) { return str; } else { return reverseStringUsingRecursion(str.substring(1)) + str.charAt(0); } } }
4.Reverse A String In Java Using Stack :
package com.crtr4u; import java.util.Stack; public class StringReverse { public static void main(String[] args) { System.out.println(reverseStringUsingStack("xyz")); } public static String reverseStringUsingStack(String str) { Stack<Character> stack = new Stack<>(); for (char c : str.toCharArray()) { stack.push(c); } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append(stack.pop()); } return sb.toString(); } }
5.Using Collections Reverse Method Reverse a String In Java :
package com.crtr4u;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StringReverse {
public static void main(String[] args) {
System.out.println(reverseStringCollectionsReverseMethod(“sdf”));
}
public static String reverseStringCollectionsReverseMethod(String str) {
List<Character> charList = new ArrayList<>();
for (char c : str.toCharArray()) {
charList.add(c);
}
Collections.reverse(charList);
StringBuilder sb = new StringBuilder();
for (char c : charList) {
sb.append(c);
}
return sb.toString();
}
}
Today we have seen various way of reversing a string in java in easy ways , happy learning .