Java StringBuilder.reverse() – Examples

In this tutorial, we will learn about the Java StringBuilder.reverse() function, and learn how to use this function to reverse this StringBuilder sequence, with the help of examples.

reverse()

StringBuilder.reverse() reverses this StringBuilder sequence inplace.

Syntax

The syntax of reverse() function is

reverse()

Returns

The function returns a reference this sequence.

Example 1 – reverse()

In this example, we will

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder("abcdef");
        System.out.println("Before reversing : " + stringBuilder.toString());
        
        stringBuilder.reverse();  
        System.out.println("After reversing  : " + stringBuilder.toString()); 
    }
}

Output

Before reversing : abcdef
After reversing  : fedcba

Example 2 – reverse() – Empty sequence

In this example, we will take an empty StringBuilder sequence and try reversing it using reverse(). Since it is empty, reversing the sequence, does not change much, the sequence is still empty.

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder();
        System.out.println("Before reversing : " + stringBuilder.toString());
        
        stringBuilder.reverse();  
        System.out.println("After reversing  : " + stringBuilder.toString()); 
    }
}

Output

Before reversing : 
After reversing  :

Conclusion

In this Java Tutorial, we have learnt the syntax of Java StringBuilder.reverse() function, and also learnt how to use this function with the help of examples.