Java StringBuffer reverse() Method

Java StringBuffer reverse() Method | The reverse() method is a built-in method in the StringBuffer that is used to reverse each and every character in the StringBuffer object. This helps to reverse the characters in the string.

The syntax for the reverse method is as follows:- public StringBuffer reverse()
Parameters: there are no parameters accepted.
Return type: string
Returns: the string which is reversed.

An example of the reverse method is as follows:-
Example-1:
String: “Hello”
After reversing: “olleH”
Example-2:
String: “Calendar”
After reversing: “radnelaC”
Example-3:
String: “098756”
After reversing: “657890”

How To Reverse A String In Java Using StringBuffer

In the below program we have created the StringBuffer object and passed the string “Books” to that and then print the same later used the reverse() method to the StringBuffer object to reverse the StringBuffer object.

public class Main {
    public static void main(String args[]) {
        StringBuffer sb = new StringBuffer("Books");
        System.out.println("StringBuffer = " + sb);
        sb.reverse();
        System.out.println("StringBuffer after reversing = " + sb);
    }
}

Output:

StringBuffer = Books
StringBuffer after reversing = skooB

Java StringBuffer reverse() Example

Here, we use an integer as an example. We pass the integer to the StringBuffer and then reverse the integer string.

public class Main {
    public static void main(String args[]) {
        StringBuffer sb = new StringBuffer("5698745123");
        System.out.println("StringBuffer = " + sb);
        sb.reverse();
        System.out.println("StringBuffer after reversing = " + sb);
    }
}

Output:

StringBuffer = 5698745123
StringBuffer after reversing = 3215478965

How To Reverse A String In Java Without Using StringBuffer

Now we use a user-defined method to reverse the string, that is we create our own method and call the same in the main method.

public class Main {
    public static void reverseStr(String str) {
        if ((str == null) || (str.length() <= 1)) {
            System.out.println(str);
        }
        else {
            System.out.print(str.charAt(str.length() - 1));
            reverseStr(str.substring(0, str.length() - 1));
        }
    }

    public static void main(String[] args) {
        String str = "Pen and pencil";
        System.out.println("String: " + str);
        System.out.print("String after reverse: ");
        reverseStr(str);
    }
}

Output:

String: Pen and pencil
String after reverse: licnep dna neP

Also see:- Reverse a String In Java Using Recursion, how to reverse a string in Java without using StringBuffer

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *