How to reverse a string with StringBuilder in java

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
}

}

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x