11 Ways to reverse a String in Java with examples

Posted by :
Last updated : February 3, 2023

Java is a versatile programming language that is widely used in the development of software applications. One of the most common tasks in programming is reversing a string, which involves switching the order of characters in a string.

In this blog post, we will explore 11 different ways to reverse a string in Java, with examples for each method. From the classic approach of using loops and recursion, to the more modern methods that leverage the power of the Java 8 Stream API and functional programming, we will cover all the different options available for reversing a string in Java.

Whether you are a beginner or an experienced Java developer, this guide will provide you with the tools and knowledge needed to tackle this fundamental programming task with confidence also helps in clearing the programming/coding interview questions on Java string.

So, without further ado, let’s dive in and discover the 11 ways to reverse a string in Java!

Different ways to reverse a string in Java

Q1: Write a program to reverse a string in java

Code:

public class ReverseString {
public static void main(String[] args) {
String input = "hello";
char[] inputArray = input.toCharArray();
for (int i = 0; i < inputArray.length / 2; i++) {
char temp = inputArray[i];
inputArray[i] = inputArray[inputArray.length - 1 - i];
inputArray[inputArray.length - 1 - i] = temp;
}
String reversed = new String(inputArray);
System.out.println("The reversed string is: " + reversed);
}
}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program.
  • The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program converts the string data type input into a character array using the toCharArray() method. This allows us to access and manipulate individual characters of the string.
  • Next, the program uses a for loop to iterate over the characters in the array.
  • The loop starts at the first character and goes up to the middle of the array. For each iteration, the program swaps the current character with the character at the corresponding position from the end of the array.
  • Finally, the program creates a new string from the reversed character array using the String constructor, and prints the reversed string to the console.
  • Note that this code is a simple way to reverse a string in java, but it has a O(n/2) complexity as it is going through half of the string. There are other ways to reverse a string in java with different complexities such as using StringBuilder or recursion.
reverse a string in java - method 1

Q2: how to reverse a string using stringbuilder in java

Code:

public class ReverseString {
public static void main(String[] args) {
String input = "hello";
StringBuilder inputBuilder = new StringBuilder();
inputBuilder.append(input);
inputBuilder = inputBuilder.reverse();
String reversed = inputBuilder.toString();
System.out.println("The reversed string is: " + reversed);
}
}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program.
  • The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program creates a new StringBuilder object and appends the input string to it using the append() method.
  • Next, the program uses the reverse() method of the StringBuilder class to reverse the characters of the string. The reverse() method modifies the StringBuilder object in place, and returns a reference to the same object.
  • Finally, the program creates a new string from the reversed stringbuilder using the toString() method, and prints the reversed string to the console.
  • This code is a more efficient way to reverse a string in java, as the StringBuilder.reverse() method has a O(n) complexity, where n is the length of the string.
reverse a string in java - method 2

Q3: how to reverse a string in java using for loop

Code:

public class ReverseString {
public static void main(String[] args) {
String input = "hello";
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
System.out.println("The reversed string is: " + reversed);
}
}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program.
  • The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program initializes a new empty string called “reversed” which is used to store the reversed string.
  • Next, the program uses a for loop to iterate over the characters in the input string, starting from the last character and going backwards to the first character. For each iteration, the program adds the current character to the “reversed” string using the concatenation operator “+=”.
  • Finally, the program prints the reversed string to the console.
  • This code snippet has a O(n) complexity, where n is the length of the string, as it is going through all the characters of the string.
reverse a string in java - method 3

Q4: how to reverse a string in java 8 using Stream API

Code:

import java.util.stream.Collectors;

public class StringReverse {

	public static String reverseString(String input) {
		return input.chars().mapToObj(i -> (char) i)
				.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).reverse().toString();
	}

	public static void main(String[] args) {
		String input = "Hello World!";
		String reversed = reverseString(input);
		System.out.println(reversed);

	}

}

Output:

The reversed string is: !dlroW olleH

Explanation:

  • This code uses the StringBuilder class to create a new object with the input string, then calls the reverse() method on that object to reverse the order of the characters, and finally calls the toString() method to convert the reversed StringBuilder object back into a String.
  • Here, input.chars() returns an IntStream containing the ASCII values of the characters in the input string.
  • Then the mapToObj() method is used to convert each ASCII value into a corresponding character.
  • Finally, the collect() method is used to concatenate all of the characters into a single string, in reverse order.
reverse a string in java - method 4

Q5: how to reverse the words in a given string sentence in java

Code:

public class ReverseWords {
public static void main(String[] args) {
String input = "Hello World";
String[] words = input.split("\\s+");
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]).append(" ");
}
System.out.println("The reversed sentence is: " + reversed.toString().trim());
}
}

Output:

The reversed sentence is: World Hello

Explanation:

  • This program starts by defining a main method, which is the entry point of the program. The string sentence to be reversed is defined as “Hello World” and it is stored in a variable called “input”.
  • Then, the program splits the input string into an array of words using the split() method and the regular expression \s+ which matches one or more whitespace characters.
  • Next, the program uses a for loop to iterate over the words in the array, starting from the last word and going backwards to the first word. For each iteration, the program appends the current word to the StringBuilder object using the append() method.
  • Finally, the program uses the toString() method to convert the StringBuilder object to a String, and the trim() method to remove the trailing whitespace and prints the reversed sentence to the console.
  • This code snippet has a O(n) complexity, where n is the length of the string, as it is going through all the characters of the string.
reverse a string in java - method 5

Q6: how to reverse a string in java without using any predefined function

Code:

public class ReverseString {
public static void main(String[] args) {
String input = "hello";
char[] inputArray = input.toCharArray();
int left = 0;
int right = inputArray.length - 1;
while (left < right) {
char temp = inputArray[left];
inputArray[left] = inputArray[right];
inputArray[right] = temp;
left++;
right--;
}
String reversed = new String(inputArray);
System.out.println("The reversed string is: " + reversed);
}
}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program. The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program converts the input string into a character array using the toCharArray() method. This allows us to access and manipulate individual characters of the string.
  • Next, the program uses a while loop to iterate over the characters in the array. The loop starts with two pointers: one pointer pointing to the leftmost character of the array and the other pointer pointing to the rightmost character of the array.
  • In each iteration, the program swaps the character at the left pointer with the character at the right pointer. Then, the left pointer is incremented and the right pointer is decremented. This continues until the left pointer becomes greater than or equal to the right pointer.
  • Finally, the program creates a new string from the reversed character array using the String constructor, and prints the reversed string to the console.
  • This code snippet has a O(n) complexity, where n is the length of the string, as it is going through all the characters of the string.
reverse a string in java - method 6

Q7: how to reverse a string in java using charAt() method

Code:

public class ReverseString {
public static void main(String[] args) {
String input = "hello";
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
System.out.println("The reversed string is: " + reversed);
}
}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program. The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program initializes a new empty string called “reversed” which is used to store the reversed string.
  • Next, the program uses a for loop to iterate over the characters in the input string, starting from the last character and going backwards to the first character. For each iteration, the program adds the current character to the “reversed” string using the charAt() method and the concatenation operator “+=”.
  • Finally, the program prints the reversed string to the console.
  • This code snippet has a O(n) complexity, where n is the length of the string, as it is going through all the characters of the string.
reverse a string in java - method 7

Q8: how to reverse a string in java using recursion

Code:

public class StringReverse {

	public static String reverseString(String input) {
		if (input.isEmpty()) {
			return input;
		}
		return reverseString(input.substring(1)) + input.charAt(0);
	}

	public static void main(String[] args) {
		String input = "hello";
		String reversed = reverseString(input);
		System.out.println("The reversed string is: " + reversed);
	}

}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program. The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program defines a method reverseString() which takes a string as its parameter. This method uses recursion to reverse the input string.=
  • The base case for the recursion is when the input string is empty, in this case, the method returns the input string as it is.
  • Otherwise, the method calls itself recursively, passing a substring of the input string, obtained by removing the first character, as the parameter. The first character of the input string is then added to the end of the string returned by the recursive call.
  • Finally, the program calls the reverseString method and passes the input string as an argument and assigns the returned
reverse a string in java - method 8

Q9: how to reverse a string in java without using reverse method

Code:

public class ReverseString {
public static void main(String[] args) {
String input = "hello";
char[] inputArray = input.toCharArray();
int left = 0;
int right = inputArray.length - 1;
while (left < right) {
char temp = inputArray[left];
inputArray[left] = inputArray[right];
inputArray[right] = temp;
left++;
right--;
}
String reversed = new String(inputArray);
System.out.println("The reversed string is: " + reversed);
}
}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program. The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program converts the input string into a character array using the toCharArray() method. This allows us to access and manipulate individual characters of the string.
  • Next, the program uses a while loop to iterate over the characters in the array. The loop starts with two pointers: one pointer pointing to the leftmost character of the array and the other pointer pointing to the rightmost character of the array.
  • In each iteration, the program swaps the character at the left pointer with the character at the right pointer. Then, the left pointer is incremented and the right pointer is decremented. This continues until the left pointer becomes greater than or equal to the right pointer.
  • Finally, the program creates a new string from the reversed character array using the String constructor, and prints the reversed string to the console.
  • This code snippet has a O(n) complexity, where n is the length of the string, as it is going through all the characters of the string.
reverse a string in java - method 9

Q10: how to reverse a string array in Java

Code:

public class ReverseArray {
public static void main(String[] args) {
String[] input = {"hello", "world", "this", "is", "a", "string", "array"};
int left = 0;
int right = input.length - 1;
while (left < right) {
String temp = input[left];
input[left] = input[right];
input[right] = temp;
left++;
right--;
}
System.out.println("The reversed array is:");
for (String s : input) {
System.out.print(s + " ");
}
}
}

Output:

The reversed array is:
array string a is this world hello

Explanation:

  • This program starts by defining a main method, which is the entry point of the program. The string array to be reversed is defined as {“hello”, “world”, “this”, “is”, “a”, “string”, “array”} and it is stored in a variable called “input”.
  • Then, the program uses two pointers, one pointing to the leftmost element of the array and the other pointing to the rightmost element of the array.
  • Next, the program uses a while loop to iterate over the elements in the array. In each iteration, the program swaps the element at the left pointer with the element at the right pointer. Then, the left pointer is incremented and the right pointer is decremented. This continues until the left pointer becomes greater than or equal to the right pointer.
  • Finally, the program uses a for-each loop to print the reversed array to the console.
reverse a string in java - method 10

Q11: how to reverse a string without using reverse built in method or recursion in java

Code:

public class ReverseString {
public static void main(String[] args) {
String input = "hello";
StringBuilder reversed = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
reversed.append(input.charAt(i));
}
System.out.println("The reversed string is: " + reversed);
}
}

Output:

The reversed string is: olleh

Explanation:

  • This program starts by defining a main method, which is the entry point of the program. The string to be reversed is defined as “hello” and it is stored in a variable called “input”.
  • Then, the program creates a new StringBuilder object called “reversed” which is used to store the reversed string.
  • Next, the program uses a for loop to iterate over the characters in the input string, starting from the last character and going backwards to the first character. For each iteration, the program appends the current character to the “reversed” StringBuilder object using the append() method.
  • Finally, the program prints the reversed string to the console using the toString() method of the StringBuilder object
  • This code snippet has a O(n) complexity, where n is the length of the string, as it is going through all the characters of the string.
reverse a string in java - method 11

Follow us on YouTube for more videos on coding questions and Answers:

See you Soon:

Reversing a string in Java is a common task that can be accomplished in a variety of ways. From using loops and recursion, to the more modern methods that leverage the power of the Java 8 Stream API and functional programming, there are many different options available for reversing a string in Java.

Each method has its own advantages and disadvantages, and the best approach will depend on the specific requirements of your project. Whether you are a beginner or an experienced Java developer, this guide will help you to have the utmost knowledge on different ways to reverse a String in java which will help you to clear coding interview questions in reverse String in java. And, It is important to understand the different methods available and their performance implications, so that you can make an informed decision and choose the best approach for your project.

All the best!!!

1 thought on “11 Ways to reverse a String in Java with examples”

Leave a Comment