Method #1:
We can reverse a string in Java using the StringBuilder class, which provides a built-in reverse() method.
✅ Example using StringBuilder:
public class StringReverse(){
public static void main(String[] args){
String str = “Automation Testing”;
StringBuilder st = new StringBuilder();
st.append(str);
str = st.reverse().toString();
System.out.println(str); //output gnitseT noitamotuA
}
}
Method #2:
We can use StringBuffer in the same way as StringBuilder to reverse a string, as shown in the example below:
✅ Example using StringBuffer:
public class StringReverse {
public static void main(String[] args) {
String str = "Automation";
StringBuffer sb = new StringBuffer();
sb.append(str);
str = sb.reverse().toString();
System.out.println(str); //output noitamotuA
}
}
Method #3: Using a Loop (Without StringBuilder or StringBuffer)
We can reverse a string manually without using StringBuilder or StringBuffer by iterating through the characters in reverse order using a loop. Here’s how:
public class StringReverse {
public static void main(String[] args) {
String str = "Automation";
int len = str.length();
String reverse = "";
for(int i=len-1;i>=0;i--){
reverse+=str.charAt(i);
}
System.out.println(reverse); //output noitamotuA
}
}