Java – 4 Ways to reverse a String

In this article, we will discuss various ways to reverse a String in Java  i.e.;

1. Various ways to reverse String contents:

  1. reverse() method of StringBuffer/StringBuilder class
  2. charAt() method of String class (2-way iterating)
  3. toCharArray() method of String class (2-way iterating)
  4. recursion way

Let us move forward to discuss all possible ways to reverse a String in Java

1.1 reverse() method StringBuffer class

Below program uses reverse() method of StringBuffer class to reverse a String

Note:

  • String class doesn’t have reverse() method to reverse the String contents
  • We have choose either StringBuffer or StringBuilder for using this method
  • We need to explicitly convert String to either StringBuffer or StringBuilder before using this method
  • At last, again need to convert back to String from StringBuffer or StringBuilder for printing to console

ReverseStringUsingStringBuffer.java

package in.bench.resources.reverse.string.example;

public class ReverseStringUsingStringBuffer {

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// convert into StringBuffer
		StringBuffer sb = new StringBuffer();

		// append string contents to SB
		sb.append(urlStr);

		// use reverse() method to reverse String contents
		sb.reverse();

		// convert back to String and print to console
		System.out.println("The reverse content is : "
				+ sb.toString());
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

Tweak :- The above program can be tweaked to reverse the String by using reverse() method of StringBuilder class which is non-synchronized and hence it isn’t safe in multi-threaded environment but speed-wise faster than StringBuffer

Below program uses reverse() method of StringBuilder class to reverse a String

Note: on the very similar note,

  • String class doesn’t have reverse() method to reverse the String contents
  • We have choose either StringBuffer or StringBuilder for using this method
  • We need to explicitly convert String to either StringBuffer or StringBuilder before using this method
  • At last, again need to convert back to String from StringBuffer or StringBuilder for printing to console

ReverseStringUsingStringBuilder.java

package in.bench.resources.reverse.string.example;

public class ReverseStringUsingStringBuilder {

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// convert into StringBuilder
		StringBuilder sb = new StringBuilder();

		// append string contents to SB
		sb.append(urlStr);

		// use reverse() method to reverse String contents
		sb.reverse();

		// convert back to String and print to console
		System.out.println("The reverse content is : "
				+ sb.toString());
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

1.2 charAt() method of String class (2-way iterating)

  • Below program iterate through original String in reverse order
  • thereby storing character in reverse direction in a new String variable
  • using charAt(index) method of String class

ReverseStringUsingCharAtMethod.java

package in.bench.resources.reverse.string.example;

public class ReverseStringUsingCharAtMethod {

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";
		String reversedStr = "";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// iterate original string content in reverse order
		for(int index = urlStr.length() - 1; index >= 0; index--){
			reversedStr = reversedStr + urlStr.charAt(index);
		}

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ reversedStr);
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

Tweak :- The above program can be tweaked to reverse the String by iterating through natural order

ReverseStringUsingCharAtMethodByNaturalIteration.java

package in.bench.resources.reverse.string.example;

public class ReverseStringUsingCharAtMethodByNaturalIteration {

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";
		String reversedStr = "";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// iterate original string content in NATURAL order
		for(int index = 0; index < urlStr.length(); index++) {
			reversedStr = urlStr.charAt(index) + reversedStr;
		}

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ reversedStr);
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

1.3 toCharArray() method of String class (2-way iterating)

  • Get character array from String using toCharArray() method of String class
  • Iterate through character array in reverse direction
  • And print to the console

ReverseStringUsingToCharArrayMethod.java

package in.bench.resources.reverse.string.example;

public class ReverseStringUsingToCharArrayMethod {

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";
		String reversedStr = "";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// get character array using toCharArray() method
		char[] originalCharArr = urlStr.toCharArray();

		// iterate original character array in reverse order
		for(int index = originalCharArr.length - 1;
				index >= 0; index--){
			reversedStr = reversedStr + urlStr.charAt(index);
		}

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ reversedStr);
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

Tweak :- Very similarly, above program can be tweaked to reverse the String by iterating through natural order

ReverseStringUsingToCharArrayMethodByNaturalIteration.java

package in.bench.resources.reverse.string.example;

public class ReverseStringUsingToCharArrayMethodByNaturalIteration{

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";
		String reversedStr = "";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// get character array using toCharArray() method
		char[] originalCharArr = urlStr.toCharArray();

		// iterate original character array in NATURAL order
		for(int index = 0; index < originalCharArr.length;
				index++) {
			reversedStr = urlStr.charAt(index) + reversedStr;
		}

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ reversedStr);
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

1.4 Using recursion

Below program uses recursion

  • First time, when recursion() method is invoked, it checks for empty string and if it satisfies this condition then empty string returned (as there is nothing to be reversed)
  • Otherwise, last character from the passed string is extracted using substring() method of String class
  • Extracted last character is added to the new string variable using string concatenation (+ operator)
  • This is repeated until all characters of the string contents is invokes the recursion() method, resursively
  • And finally when there is no more character left in the string content, then all characters added to the already defined string variable in reverse order using string concatenation is returned

ReverseStringUsingRecursion.java

package in.bench.resources.reverse.string.example;

public class ReverseStringUsingRecursion {

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";
		String reversedStr = "";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// recursion way: invoke recursive method
		reversedStr = recursiveMethod(urlStr);

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ reversedStr);
	}

	/**
	 * recursion for reversing a String contents
	 * @param str
	 * @return
	 */
	public static String recursiveMethod(String str) {

		// check for empty string
		if(str.length() == 0) {
			return "";
		}
		return str.substring(str.length() - 1)
				+ recursiveMethod(str.substring(0,
						str.length() - 1));
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

2. Tricky Interview questions:

  1. Reverse a string without using
    • temporary variables
    • chatAt() method
    • toCharArray() method
    • reverse() method of StringBuffer/StringBuilder
  2. Reversing the complete sentence instead of single word (mirror image)
    Example: This is Java weblog –> golgew avaJ si sihT
  3. Reverse of a exact string in a sentence
    Example: Bench Resources –> hcneB secruoseR
  4. Reverse sentence in wrong order
    Example: BenchResources.Net is committed to provide good Java tutorials –> tutorials Java good provide to committed is BenchResources.Net)

Let us move forward to discuss all possible ways to reverse a String in Java

2.1 Reverse a string

  • without using any temporary variable (3 variable concept)
  • chatAt() or toCharArray() method of String class
  • reverse() method of StringBuffer/StringBuilder

ReverseStringInterview.java

package in.bench.resources.reverse.string.example;

public class ReverseStringInterview {

	public static void main(String[] args) {

		// string value
		String urlStr = "BenchResources.Net";
		String reversedStr = "";

		// print original string content to console
		System.out.println("The original string content is : "
				+ urlStr);

		// iterate original string content in NATURAL order
		for (int i = 0; i < urlStr.length(); i++ ){

			// use subString() iteratively
			reversedStr = reversedStr + urlStr.substring(
					urlStr.length() - i - 1,
					urlStr.length() - i);
		}

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ reversedStr);
	}
}

Output:

The original string content is : BenchResources.Net
The reverse content is : teN.secruoseRhcneB

2.2 Reversing complete sentence

  • complete sentence is reversed instead of single word
  • here, complete-sentence is reversed as well as individual-words
  • Example :- This is Java weblog –> golgew avaJ si sihT

ReverseStringSentence.java

package in.bench.resources.reverse.string.example;

public class ReverseStringSentence {

	public static void main(String[] args) {

		// string value
		String strSentence = "This is Java weblog";

		// reversed content stored in SB
		StringBuffer sbReversed = new StringBuffer();

		// print original string content to console
		System.out.println("The original string content is : "
				+ strSentence);

		// split sentence by setting space as delimiter
		String[] splittedString = strSentence.split(" ");

		// iterating String[] array
		for(int i = splittedString.length - 1; i >= 0; i--) {

			// temp variable
			String reversedStr = "";

			// iterate each string content in reverse order
			for(int index = splittedString[i].length() - 1;
					index >= 0; index--) {
				reversedStr = reversedStr +
						splittedString[i].charAt(index);
			}

			// append to SB + an extra space
			sbReversed.append(reversedStr).append(" ");
		}

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ sbReversed.toString());
	}
}

Output:

The original string content is : This is Java weblog
The reverse content is : golbew avaJ si sihT

2.3 Reverse of a exact string

  • Reverse of string in a sentence
  • without altering order of the sentence
  • Example :- Bench Resources –> hcneB secruoseR

ReverseExactStringSentence.java

package in.bench.resources.reverse.string.example;

public class ReverseExactStringSentence {

	public static void main(String[] args) {

		// string value
		String strSentence = "Bench Resources";

		// reversed content stored in SB
		StringBuffer sbReversed = new StringBuffer();

		// print original string content to console
		System.out.println("The original string content is : "
				+ strSentence);

		// split sentence by setting space as delimiter
		String[] splittedString = strSentence.split(" ");

		// iterating String array
		for(int i = splittedString.length - 1; i >= 0; i--) {

			// append to SB + an extra space
			sbReversed.append(splittedString[i]).append(" ");
		}

		// print reversed content to console
		System.out.println("The reverse content is : "
				+ sbReversed.reverse().toString());
	}
}

Output:

The original string content is : Bench Resources
The reverse content is :  hcneB secruoseR

2.4 Reverse the sentence

  • Reverse sentence
  • individual words are NOT reversed
  • but complete sentence is reversed i.e.; in wrong order)
  • Example :- BenchResources.Net is committed to provide good Java tutorials –> tutorials Java good provide to committed is BenchResources.Net

ReverseSentenceInWrongOrder.java

package in.bench.resources.reverse.string.example;

public class ReverseSentenceInWrongOrder {

	public static void main(String[] args) {

		// string value
		String strSentence = "BenchResources.Net is committed "
				+ "to provide good Java tutorials";

		// reversed content stored in SB
		StringBuffer sbReversed = new StringBuffer();

		// print original string content to console
		System.out.println("The original string content is : "
				+ strSentence);

		// split sentence by setting space as delimiter
		String[] splittedString = strSentence.split(" ");

		// iterating String array
		for(int i = splittedString.length - 1; i >= 0; i--) {

			// append to SB + an extra space
			sbReversed.append(splittedString[i]).append(" ");
		}

		// print reversed content to console
		System.out.println("The reverse string content is  : "
				+ sbReversed.toString());
	}
}

Output:

The original string content is : BenchResources.Net is committed
to provide good Java tutorials

The reverse string content is  : tutorials Java good provide
to committed is BenchResources.Net

Hope, you found this article very helpful. If you have any suggestions or want to contribute any other ways of reversing a string or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Split String in 3 different ways based on delimiter
Java - String indexOf() method