- Method 1 - String Builder / String Buffer
public class Method1 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Amritanshu");
StringBuffer sbf = new StringBuffer("Rawat");
System.out.println("String Builder: "+ sb.reverse().toString());
System.out.println("String Buffer: " + sbf.reverse().toString());
}
}
- Method 2 - String Concatenation
public class Method2 {
public static void main(String[] args) {
String name = "Amritanshu Dev Rawat";
String rev = "";
for(int i = name.length()-1;i>=0;i--) {
rev += name.charAt(i);
}
System.out.println(rev);
}
}
- Method 3 - Character Array
public class Method3 {
public static void main(String[] args) {
String name = "Amritanshu";
char[] charName = name.toCharArray();
for(int i = charName.length -1; i>=0;i--) {
System.out.print(name.charAt(i));
}
}
}
import java.util.Stack;
public class Method4 {
public static void main(String[] args) {
String name = "Amritanshu";
Stack<Character> charStack = new Stack<Character>();
char[] ch = name.toCharArray();
for (int i = 0; i < name.length(); i++) {
charStack.push(ch[i]);
}
int k =0;
while(!charStack.isEmpty()) {
ch[k++] = charStack.pop();
}
System.out.println(String.copyValueOf(ch));
}
}
public class Method5 {
public static void main(String[] args) {
String name = "Amritanshu Dev Rawat";
char[] c = name.toCharArray();
int begin=0;
int end=c.length-1;
char temp;
while(end>begin){
temp = c[begin];
c[begin]=c[end];
c[end] = temp;
end--;
begin++;
}
System.out.println(String.valueOf(c));
}
}