Java Reverse a String Program
- Reverse a String using iterative method
- Reverse a String using StringBuilder
What is Reversing a String
Reversing a string means changing the order of characters in a string. For example, the reverse of the string "Hello World" is "dlroW olleH".
Java Reverse String using Iterative Method
In this method, we will use a for loop to iterate through the string from the last character to the first character and append each character to a new string to reverse the string. We will follow the below steps to reverse a string using the iterative method:
- Initialize a new string variable to store the reversed string.
- Iterate through the string from the last character to the first character using a for loop.
- Append each character of the string to the new string.
- Print the reversed string.
public class ReverseStringExample {
public static void main(String[] args) {
String str = "Hello World";
String reversedString = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversedString += str.charAt(i);
}
System.out.println("Reversed String: " + reversedString);
}
}
Reversed String: dlroW olleHTime Complexity: O(n) - Linear Time as we are iterating through the string once.
Space Complexity: O(n) - Linear Space as we are using a new string to store the reversed string.
In this code, we have used a for loop. In that we have initialized the loop i with the length of the string minus 1. And add the condition i >= 0 to iterate through the string from the last character to the first character. Inside the loop, we append each character of the string using the charAt() method to the reversedString variable. Finally, we print the reversed string.
Java Reverse String using StringBuilder
In this method, we will use the StringBuilder class to reverse a string. The StringBuilder class provides a reverse() method that can be used to reverse a string. Here is the Java code to reverse a string using the StringBuilder class:
public class ReverseStringExample {
public static void main(String[] args) {
String str = "Hello World";
StringBuilder reversedString = new StringBuilder(str).reverse();
System.out.println("Reversed String: " + reversedString);
}
}
Reversed String: dlroW olleHTime Complexity: O(n) - Linear Time as the reverse() method iterates through the string once.
Space Complexity: O(n) - Linear Space as we are using the StringBuilder object to store the reversed string.
In this code, we have created a StringBuilder object with the input string and used the reverse() method to reverse the string. Finally, we print the reversed string.
- Recommended Links
- Selenium Interview Questions