1. Write a java program to reverse a string?
The provided Java program demonstrates various techniques to reverse a given string. It offers three methods for string reversal:
package com.javainfotech;
public class StringReverse {
public static void main(String[] args) {
//Using StringBuffer
String res = reverseUsingStringBuffer("JavaInfotech");
System.out.println("Reverse String - "+res);
String result = reverseUsingIterate("JavaInfotech");
System.out.println("Reverse String - "+result);
String results = reverseUsingRecursive("JavaInfotech");
System.out.println("Reverse String - "+results);
}
//Using StringBuffer
public static String reverseUsingStringBuffer(String str){
StringBuffer sb = new StringBuffer(str);
return sb.reverse().toString();
}
//Using Iterating
public static String reverseUsingIterate(String str){
char[] ch = str.toCharArray();
String s ="";
for(int i=ch.length-1;i>=0;i--){
s = s+ch[i];
}
return s;
}
//Using Recursive
public static String reverseUsingRecursive(String str){
if((str==null) || (str.length()<=1)){
return str;
}
return reverseUsingRecursive(str.substring(1))+str.charAt(0);
}
}