Description

On this document we will be showing a java example on how to use the StringBuilder reverse() method of StringBuilder Class. Basically the reverse() method causes this character sequence to be replaced by the reverse of the sequence. If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation. Thus, the order of the high-low surrogates is never reversed. Let n be the character length of this character sequence (not the length in char values) just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.

Method Syntax

public StringBuilder reverse()

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

The reverse() method returns this StringBuilder object with it’s character reversed.

Compatibility

Requires Java 1.5 and up

Java StringBuilder reverse() Example

Below is a java code demonstrates the use of reverse() method of StringBuilder class. The example presented might be simple however it shows the behaviour of the reverse() method.

package com.javatutorialhq.java.examples;

/*
 * A java example source code to demonstrate
 * the use of reverse() method of StringBuilder class
 */

public class StringBuilderReverseExample {

	public static void main(String[] args) {

		// initialize the StringBuilder object
		StringBuilder sb = new StringBuilder("javatutorialhq.com");
		System.out.println("Contents of StringBuilder:" + sb);

		// reverse the character sequence
		sb.reverse();
		System.out.println("New contents of StringBuilder:" + sb);
	}
}

The above java example source code demonstrates the use of reverse() method of StringBuilder class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the string buffer. Then we use the reverse method to actually reverse the contents of the character sequence.

Sample Output

Below is the sample output when you run the above example.

StringBuilder reverse() example output