Examples
- Java Program to Count Number of Digits in Number (Integer Length)
- Java Program to Reverse a String (4 Methods)
- How to Reverse an Array in Java? Array Reverse Program
- How to Find Power of a Number in Java? 4 Programs
- How to Find Factors of a Number in Java? Factors Program
- Check Disarium Number in Java (3 Easy Programs)
- Find Keith Number in Java (Easy Programs)
- Happy Number in Java (Easy Programs With Logic)
- Find Sunny Number in Java (Easy Programs)
Java Program to Reverse a String (4 Methods)
Strings in Java are a fundamental data type and are used extensively in programming for various tasks. One common operation you may encounter is the need to reverse a string in Java.
Whether you're building a text manipulation application, solving a coding challenge, or simply trying to understand string manipulation better, knowing how to reverse a string is a valuable skill.
In this tutorial, we will write a Java program to reverse a string, step by step. We will cover multiple approaches, from the simplest to more advanced techniques, ensuring that you have a solid understanding of the topic by the end of this guide.
Concepts to Learn:
Java Program to Reverse a String Using StringBuilder
Here is a Java prorgram to reverse each word in string using the StringBuilder:
Code
public class ReverseString {
public static void main(String[] args) {
String input = "Hello, World!";
// Create a StringBuilder object and append the input string
StringBuilder reversed = new StringBuilder(input);
// Use the reverse() method to reverse the string
reversed.reverse();
// Convert the StringBuilder back to a String
String result = reversed.toString();
// Print the reversed string
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + result);
}
}
Output
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Explanation
-
In this program, we start with the input string "Hello, World!".
-
We create a StringBuilder object called reversed and initialize it with the input string.
-
Using the reverse() method of the StringBuilder class, we reverse the content of the reversed object.
-
Finally, we convert the StringBuilder back to a regular string using toString() and print both the original and reversed strings.
In this example, we have successfully reversed the input string using the StringBuilder approach, which is one of the most efficient ways to reverse a string in Java.
String Reverse Program in Java Using while Loop
In this method, we will write a Java program to find reverse of the string using while loop and character array:
Code
public class ReverseString {
public static void main(String[] args) {
String input = "Hello, World!";
// Convert the input string to a character array
char[] charArray = input.toCharArray();
// Initialize pointers for the start and end of the array
int start = 0;
int end = charArray.length - 1;
// Reverse the character array
while (start < end) {
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}
// Create a new string from the reversed character array
String result = new String(charArray);
// Print the reversed string
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + result);
}
}
Output
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Explanation
-
In this program, we start with the input string "Hello, World!".
-
We convert the input string into a character array using toCharArray().
-
We initialize two pointers, start and end, to the beginning and end of the array, respectively.
-
Using a while loop, we swap characters between start and end positions until start is less than end, effectively reversing the character array in place.
-
After reversing the array, we create a new string from the reversed character array using the String constructor.
-
Finally, we print both the original and reversed strings.
Java Program to Reverse The String Using Recursion
Now, let’s write a Java program to reverse a string using recursion:
Code
public class ReverseString {
public static void main(String[] args) {
String input = "Hello, World!";
// Call the reverseString method to reverse the input string
String result = reverseString(input);
// Print the reversed string
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + result);
}
// Recursive method to reverse a string
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Output
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Explanation
-
In this program, we start with the input string "Hello, World!".
-
We define a recursive method reverseString that takes a string str as its parameter.
-
Inside the reverseString method, we have a base case: if the input string str is empty, we return it as is.
-
In the recursive case, we call reverseString on a substring of str starting from the second character (str.substring(1)) and concatenate the first character (str.charAt(0)) at the end. This effectively reverses the string by breaking it down into smaller substrings and reversing them recursively.
-
Finally, we call the reverseString method with the input string and print both the original and reversed strings.
Reverse a String in Java Using Stream API
Lastly, we will write the string reverse program using the Stream API in Java 8:
Code
import java.util.stream.Collectors;
public class ReverseString {
public static void main(String[] args) {
String input = "Hello, World!";
// Use the Java 8 Stream API to reverse the input string
String result = new StringBuilder(input).reverse().toString();
// Print the reversed string
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + result);
}
}
Output
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Explanation
-
In this program, we start with the input string "Hello, World!".
-
We use the Java 8 Stream API to reverse the string in a concise manner.
-
First, we create a StringBuilder object and initialize it with the input string.
-
Then, we call the reverse() method on the StringBuilder object to reverse its content.
-
Finally, we use toString() to convert the reversed StringBuilder back to a regular string and store it in the result variable.
-
We print both the original and reversed strings.
In this example, we've reversed the input string using the Java 8 Stream API, which provides a more modern and concise way to achieve the same result as the previous methods. The code is simpler and more readable, making it a preferred choice when working with Java 8 or later versions.
Learn Next: