How to reverse a String in Java – 7 ways with Examples

In this article, we illustrate several methods to reverse a String.

Note that Strings in Java are immutable – we cannot reverse the characters in the given String object itself. Instead, to reverse a String in Java, we must generate a new String consisting of the characters of the given String in reverse order.

Solution 1 – Using Recursion

public static String recursionReverse(String s) {
	int length = s.length();
	
	switch(length) {
	case 0: return "";
	case 1: return s;
	default: return s.substring(length - 1) + recursionReverse(s.substring(0, length - 1));
	}
}

Solution 2 – Using a Stack

import java.util.Stack;
...

public static String stackReverse(String s) {
	Stack<Character> stack = new Stack<>();
	int length = s.length();
	
	for(int i = 0; i < length; i++) {
		stack.push(s.charAt(i));
	}
	
	String result = "";   	
	
	while (!stack.empty()) {
		result += stack.pop();
	}
	
	return result;
}

Solution 3 – Using an ArrayList

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
...

public static String arrayListReverse(String s) {
	List<Character> list = s.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
		
	Collections.reverse(list);
	
	return list.stream().map(String::valueOf).collect(Collectors.joining());
}	

Solution 4 – Using char[]

public static String charArrayReverse(String s) {
	int length = s.length();
	char[] reversed = new char[length];

	for(int i = 0; i < length; i++) {
		reversed[i] = s.charAt(length - i - 1);
	}

	return new String(reversed);
}	

Solution 5 – Using a Deque

import java.util.Deque;
import java.util.LinkedList;
import java.util.stream.Collectors;
...

public static String dequeReverse(String s) {
	Deque<Character> deque = new LinkedList<>();
	int length = s.length();
	
	for(int i = 0; i < length; i++) {
		deque.addFirst(s.charAt(i));
	}
	
	return deque.stream().map(String::valueOf).collect(Collectors.joining());
}

Solution 6 – Using a StringBuffer

public static String stringBufferReverse(String s) {
	StringBuffer buffer = new StringBuffer();
	int length = s.length();
	
	for(int i = 0; i < length; i++) {
		buffer.insert(0, s.charAt(i));
	}
	
	return buffer.toString();
}

Solution 7 – Using a StringBuilder

public static String stringBuilderReverse(String s) {
	return new StringBuilder(s).reverse().toString();
}

Conclusion

We looked at several ways to reverse a String in Java.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.