Code snippet to reverse a String in JAVA. There are many ways to achieve this by using a for loop, by using a built in function provided by the JAVA or by using recursion.
Reverse string using for loop
import java.util.*;
public class ReverseString {
public static void main(String[] args){
Scanner input = new Scanner (System.in);
String str = input.next();
String reverse = "";
for(int i=str.length()-1;; i>=0; i--){
reverse += str.charAt(i);
}
System.out.println(reverse);
}
}
Reverse string using Recursion
public class ReverseString {
public static void main(String[] args) {
String str = "Reverse String";
String reversed = reverseString(str);
System.out.println("Reversed string: " + reversed);
}
public static String reverseString(String str)
{
if (str.isEmpty())
return str;
//Recursion function call
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Reverse String using Native Method
public class ReverseString {
public static void main(String[] args) {
String str = "Reverse String";
String reversed = new StringBuffer(str).reverse().toString();
System.out.println("Reversed string: " + reversed);
}
}