In this blog, we’ll explore the process of reversing strings in Java step by step and discuss the Java methods and techniques that enable reversal. So, are you ready to explore the examples of reversing strings in Java? Let’s jump in and understand this concept together!
Table of Contents
Want to learn Java, watch the video below
What is String in Java?
In Java, a string is a sequence of characters that represent text. It’s a class in Java’s standard library that allows you to manipulate and store textual data. Strings are immutable, meaning their values cannot be changed after creation.
You can create a String using double quotes, like “Hello, World!”. Java provides numerous methods for string manipulation, such as concatenation, length retrieval, and substring extraction. Here’s a simple example:
public class StringExample {
public static void main(String[] args) {
String greeting = "Hello";
String name = "Intellipaat Welcomes You";
String message = greeting + ", " + name + "!";
System.out.println(message); }
}
// Output: Hello, Intellipaat Welcomes You!
What is String Reversal in Java
In Java, string reversal is the process of flipping the order of characters in a string. To achieve this, you can use a simple loop or the built-in StringBuilder class. String reversal in Java can be achieved in the following ways:
Different Ways of Reversing Strings in Java
Reversing strings in Java offers diverse methods, from basic loops and StringBuilder to advanced techniques like recursion and stacks. Let us first discuss how you can reverse a string in Java using loops.
Reversing Strings in Java Using Loops
To reverse strings in Java using loops, we use either ‘for’ or ‘while’ loops, making it beginner-friendly. These loops make it easier to traverse characters backward, which makes it simple and effective to create a reversed string.
Reversing Strings in Java Using While Loop
Reversing strings in Java using a while loop is a simple process. We use a ‘while’ loop to iterate through the characters of a string in reverse order. Let us see how it works:
public class StringReversal {
public static void main(String[] args) {
String original = "Intellipaat";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println(" Reversed: " + reversed);
}
public static String reverseString(String input) {
int length = input.length();
String reversed = "";
int i = length - 1;
while (i >= 0) {
reversed += input.charAt(i);
i--;
}
return reversed;
}
}
Let us now discuss how this code works step by step:
Class Declaration
public class StringReversal {
- This declares a class named StringReversal. In Java, the filename must match the class name, so this should be in a file named StringReversal.java.
Main Method
public static void main(String[] args) {
- The main method is the entry point of the program. It takes an array of strings as arguments.
Variable Declaration and Initialization
String original = "Intellipaat";
String reversed = reverseString(original);
- It declares two strings, original with the value “Intellipaat” and reversed. The reverseString method is called to reverse the original string.
Printing Original and Reversed Strings:
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
- Outputs the original and reversed strings to the console
Reverse String Method
public static String reverseString(String input) {
int length = input.length();
String reversed = "";
int i = length - 1;
while (i >= 0) {
reversed += input.charAt(i);
i--;
}
return reversed;
}
- This method takes a string (input) as an argument and returns the reversed string.
- It calculates the length of the input string.
- A variable reversed is initialized to an empty string.
- A ‘while’ loop is used to iterate through the characters of the input string in reverse order.
- Inside the loop, each character is appended to the reversed string.
- The loop continues until it reaches the first character.
- The reversed string is then returned.
Output
- So, the program takes the string “Intellipaat,” reverses it using the reverseString method, and prints both the original and reversed strings to the console.
- In this case, “Intellipaat” becomes “taapilletnI“.
Get 100% Hike!
Master Most in Demand Skills Now!
Reversing Strings in Java Using the “For Loop”
Reversing Strings in Java using a “For loop” is a common technique for reversing the order of characters in a string. Let us have a look at an example to understand it better.
public class StringReversal {
public static void main(String[] args) {
String original = "Intellipaat";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
public static String reverseString(String input) {
int length = input.length();
String reversed = "";
for (int i = length - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
return reversed;
}
}
Let us have a look at how this code works, what output it produces, and why!
Class Declaration
public class StringReversal {
- Declares a class named StringReversal.
Main Method
public static void main(String[] args) {
- The main method, the entry point of the program.
Variable Declaration and Initialization
String original = "Intellipaat";
String reversed = reverseString(original);
- Declares a string original with the value “Intellipaat” and initializes a string reversed by calling the reverseString method.
Printing Original and Reversed Strings
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
- Outputs the original and reversed strings to the console.
Reverse String Method Using “for” Loop
public static String reverseString(String input) {
int length = input.length();
String reversed = "";
for (int i = length - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
return reversed;
}
- This method takes a string (input) as an argument and returns the reversed string.
- It calculates the length of the input string.
- A ‘for’ loop is used to iterate through the characters of the input string in reverse order.
- Inside the loop, each character is appended to the reversed string.
- The loop continues until it reaches the first character.
- The reversed string is then returned.
Output
When you run the program, it will print:
Original: Intellipaat
Reversed: taapilletnI
- The original string is “Intellipaat,” and the reversed string is “taapilletnI,” achieved using a “for loop” to reverse the order of characters.
Interested in learning Java? Enroll in our Java Training now!
Reversing Strings in Java Using the StringBuilder
Reversing Strings in Java Using StringBuilder is a more efficient method compared to using loops. The StringBuilder class provides a reverse() method, making the reversal process simpler and faster. Here’s an example:
public class StringReversal {
public static void main(String[] args) {
String original = "Intellipaat";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
public static String reverseString(String input) {
// Create a StringBuilder object and initialize it with the original string
StringBuilder stringBuilder = new StringBuilder(input);
// Use the reverse() method to reverse the contents of the StringBuilder
stringBuilder.reverse();
// Convert the reversed StringBuilder back to a string
return stringBuilder.toString();
}
}
The first four steps are similar to what we were doing prior (declaring the class, main method, variable declaration and initialization, and printing original and reversed strings). Now let us discuss the next step:
Reverse String Method
public static String reverseString(String input) {
// Create a StringBuilder object and initialize it with the original string
StringBuilder stringBuilder = new StringBuilder(input);
// Use the reverse() method to reverse the contents of the StringBuilder
stringBuilder.reverse();
// Convert the reversed StringBuilder back to a string
return stringBuilder.toString();
}
- This method takes a string (input) as an argument and returns the reversed string.
- It creates a StringBuilder object, initializing it with the original string.
- The reverse() method of StringBuilder is used to reverse the contents of the StringBuilder.
- Finally, the reversed StringBuilder is converted back to a string using the toString() method and returned.
Output
- When you run this program, it will print-
Original: Intellipaat
Reversed: taapilletnI
Reversing Strings in Java Using the Substring() Method
Reversing strings in Java using the substring() method is a concise approach. The substring() method allows us to extract portions of a string. Here’s a simple example-
public class StringReversal {
public static void main(String[] args) {
String original = "Intellipaat";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println(" Reversed: " + reversed);
}
public static String reverseString(String input) {
int length = input.length();
String reversed = "";
for (int i = length - 1; i >= 0; i--) {
reversed += input.substring(i, i + 1);
}
return reversed;
}
}
Reverse String Method
public static String reverseString(String input) {
int length = input.length();
String reversed = "";
for (int i = length - 1; i >= 0; i--) {
reversed += input.substring(i, i + 1);
}
return reversed;
}
- This method takes a string (input) as an argument and returns the reversed string.
- Calculates the length of the input string.
- Utilizes a ‘for’ loop to iterate through the characters of the input string in reverse order.
- Inside the loop, the substring() method is used to extract each character individually and append it to the reversed string.
- The loop continues until it reaches the first character.
- The reversed string is then returned.
- So, the program takes the string “Intellipaat,” reverses it using the reverseString method, and prints both the original and reversed strings to the console. In this case, “Intellipaat” becomes “taapailletnI”.
Check out the Top Java Interview Questions to ace your next interview!
Reversing Strings in Java Using an ArrayList Object
Reversing strings in Java using an ArrayList object is another method to reverse a string. Have a look at the below example to understand it better.
import java.util.ArrayList;
public class StringReversal {
public static void main(String[] args) {
String original = "Intellipaat";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println(" Reversed: " + reversed);
}
public static String reverseString(String input) {
// Convert the string to a list of characters
ArrayList<Character> charList = new ArrayList<>();
for (char c : input.toCharArray()) {
charList.add(c);
}
// Reverse the list
for (int i = 0; i < charList.size() / 2; i++) {
char temp = charList.get(i);
charList.set(i, charList.get(charList.size() - 1 - i));
charList.set(charList.size() - 1 - i, temp);
}
// Convert the list back to a string
StringBuilder reversed = new StringBuilder(charList.size());
for (char c : charList) {
reversed.append(c);
}
return reversed.toString();
}
}
Let us see how this code works:
Importing the ArrayList class
import java.util.ArrayList;
- This line imports the ArrayList class from the java.util package, allowing the use of dynamic arrays.
Class Declaration
public class StringReversal {
- This declares a class named StringReversal. In Java, the filename must match the class name, so this should be in a file named StringReversal.java.
Main Method
public static void main(String[] args) {
The main method is the entry point of the program. It takes an array of strings as arguments.
Variable Declaration and Initialization
String original = “Intellipaat”;
String reversed = reverseString(original);
- It declares two strings, original with the value “Intellipaat” and reversed. The reverseString method is called to reverse the original string.
Printing Original and Reversed Strings
System.out.println(“Original: ” + original);
System.out.println(” Reversed: ” + reversed);
- Outputs the original and reversed strings to the console.
Reverse String Method
public static String reverseString(String input) {
// Convert the string to a list of characters
ArrayList<Character> charList = new ArrayList<>();
for (char c : input.toCharArray()) {
charList.add(c);
}
// Reverse the list
for (int i = 0; i < charList.size() / 2; i++) {
char temp = charList.get(i);
charList.set(i, charList.get(charList.size() - 1 - i));
charList.set(charList.size() - 1 - i, temp);
}
// Convert the list back to a string
StringBuilder reversed = new StringBuilder(charList.size());
for (char c : charList) {
reversed.append(c);
}
return reversed.toString();
}
- This method takes a string (input) as an argument and returns the reversed string.
- It converts the input string into an ArrayList of characters.
- A ‘for-each’ loop is used to iterate through the characters of the input string and add them to the ArrayList.
- Another loop is used to reverse the elements in the ArrayList by swapping characters from the beginning with characters from the end.
- The reversed characters are then appended to a StringBuilder.
- The method returns the reversed string.
Output
- So, the program takes the string “Intellipaat,” reverses it using the reverseString method, and prints both the original and reversed strings to the console. In this case, “Intellipaat” becomes “taapilletnI”.
Reversing Strings in Java Using Stack
Reversing strings in Java using a stack is a method that utilizes the Stack data structure. Let us see how it can help to reverse a string in Java.
import java.util.Stack;
public class StringReversalWithStack {
public static void main(String[] args) {
String original = "IntellipaatStack";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
public static String reverseString(String input) {
Stack<Character> stack = new Stack<>();
// Push each character onto the stack
for (char c : input.toCharArray()) {
stack.push(c);
}
// Pop characters from the stack to form the reversed string
StringBuilder reversed = new StringBuilder();
while (!stack.isEmpty()) {
reversed.append(stack.pop());
}
return reversed.toString();
}
}
Let us now understand how this code functions:
Reverse String Method
public static String reverseString(String input) {
Stack<Character> stack = new Stack<>();
// Push each character onto the stack
for (char c : input.toCharArray()) {
stack.push(c);
}
// Pop characters from the stack to form the reversed string
StringBuilder reversed = new StringBuilder();
while (!stack.isEmpty()) {
reversed.append(stack.pop());
}
return reversed.toString();
}
- This method takes a string (input) as an argument and returns the reversed string using a stack.
- It creates a Stack of characters named stack.
- A ‘for-each’ loop is used to push each character of the input string onto the stack.
- Another ‘while’ loop pops characters from the stack and appends them to a StringBuilder to form the reversed string.
- The reversed string is obtained by converting the StringBuilder back to a string using toString().
Output
- The program takes the string “IntellipaatStack,” reverses it using a stack in the reverseString method, and prints both the original and reversed strings to the console.
- The result is “IntellipaatStack” becoming “kcatSataillepI”.
Reversing Strings in Java Using Reverse Iteration
Reversing Strings in Java Using Reverse Iteration is a straightforward process. It involves iterating through the characters of a string in reverse order and creating a new string with those characters. Here’s an example:
public class ReverseIterationExample {
public static void main(String[] args) {
String original = "JavaReversal";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
public static String reverseString(String input) {
int length = input.length();
StringBuilder reversedBuilder = new StringBuilder();
for (int i = length - 1; i >= 0; i--) {
reversedBuilder.append(input.charAt(i));
}
return reversedBuilder.toString();
}
}
Let us understand how this code reverses the string:
Reverse String Method
public static String reverseString(String input) {
int length = input.length();
StringBuilder reversedBuilder = new StringBuilder();
for (int i = length - 1; i >= 0; i--) {
reversedBuilder.append(input.charAt(i));
}
return reversedBuilder.toString();
}
- This method takes a string (input) as an argument and returns the reversed string.
- It calculates the length of the input string.
- Initializes a StringBuilder named reversedBuilder to efficiently manipulate characters.
- A ‘for’ loop is used to iterate through the characters of the input string in reverse order.
- Inside the loop, each character is appended to the reversedBuilder.
- The loop continues until it reaches the first character.
- The reversed string is obtained by converting the StringBuilder back to a string using toString().
- So, the program takes the string “Intellipaat,” reverses it using the reverseString method, and prints both the original and reversed strings to the console. The result is “Intellipaat” becoming “taapilletnI”.
Reversing Strings in Java Using Recursion
Reversing Strings in Java Using Recursion is a technique where a method calls itself to achieve the reversal. Here’s a breakdown of the code:
In this example, “Recursion” is reversed using recursion, resulting in “noisruceR.” The method breaks down the problem into smaller sub-problems until it reaches the base case, providing an elegant way to reverse a string.
public class StringReversal {
public static void main(String[] args) {
String original = "Recursion";
String reversed = reverseString(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
public static String reverseString(String input) {
if (input.isEmpty()) {
return input;
} else {
return reverseString(input.substring(1)) + input.charAt(0);
}
}
}
- This method takes a string (input) as an argument and returns the reversed string using recursion.
- It checks if the input string is empty. If true, it returns the input as is.
- If not, it calls itself with the substring excluding the first character (input.substring(1)), and then appends the first character (input.charAt(0)).
- This recursive process continues until the base case (empty string) is reached.
The Best Way to Reverse a String in Java
The best way to reverse a string in Java is by using the StringBuilder class. Unlike traditional methods involving loops or recursion, StringBuilder provides a more efficient and straightforward solution.
When you concatenate or reverse strings, StringBuilder minimizes unnecessary memory overhead and performs the reversal in-place, making it faster and more memory-efficient. It’s a go-to choice for string manipulations due to its mutable nature, allowing characters to be modified directly. This method is not only efficient but also simplifies the code, enhancing readability.
Conclusion
In conclusion, mastering string reversal in Java is crucial for any developer. Therefore, we have covered everything from basic loop methods to advanced recursion and the efficiency of StringBuilder. The simplicity of the presented code ensures accessibility, while the performance-focused approach with StringBuilder highlights the importance of choosing the right technique. Whether you’re a beginner or seeking optimization, this blog equips you with the knowledge to confidently reverse strings in Java. As a fundamental skill, string reversal is a gateway to understanding essential concepts in Java programming.