Multiple techniques exist for reversing a String in Java. Options include utilizing StringBuffer, StringBuilder, iteration, and more. Let's explore the various methods available for reversing Strings in Java.
1) By Using StringBuilder / StringBuffer Class
File: StringFormatter.java
public class StringFormatter {
public static String reverseString(String str){
StringBuilder sb=new StringBuilder(str);
sb.reverse();
return sb.toString();
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.reverseString("my name is khan"));
System.out.println(StringFormatter.reverseString("I am sonoo jaiswal"));
}
}
Output:
nahk si eman ym
lawsiaj oonos ma I
2) By Using Reverse Iteration
File: StringFormatter.java
public class StringFormatter {
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.reverseString("my name is khan"));
System.out.println(StringFormatter.reverseString("I am sonoo jaiswal"));
}
}
Output:
nahk si eman ym
lawsiaj oonos ma I
Filename: StringReversal.java
public class StringReversal {
// Approach 1: Using StringBuilder
public static String reverseWithStringBuilder(String str) {
// Step 1: Create a new StringBuilder object
StringBuilder stringBuilder = new StringBuilder();
// Step 2: Iterate over each character in the input string in reverse order
for (int i = str.length() - 1; i >= 0; i--) {
// Step 3: Append the current character to the StringBuilder
stringBuilder.append(str.charAt(i));
}
// Step 4: Convert the StringBuilder object to a string and return it
String reversedString = stringBuilder.toString();
return reversedString;
}
// Approach 2: Using a char array
public static String reverseWithCharArray(String str) {
// Step 1: Convert the input string to a char array
char[] charArray = str.toCharArray();
// Step 2: Create an empty char array with the same length as the input string
char[] reversedCharArray = new char[str.length()];
// Step 3: Iterate over each character in the input char array
for (int i = 0; i < str.length(); i++) {
// Step 4: Copy each character to the reversed char array in reverse order
reversedCharArray[i] = charArray[str.length() - 1 - i];
}
// Step 5: Convert the reversed char array to a string and return it
String reversedString = new String(reversedCharArray);
return reversedString;
}
// Approach 3: Using recursion
public static String reverseWithRecursion(String str) {
// Step 1: Base case - if the input string is empty, return it
if (str.isEmpty()) {
return str;
}
// Step 2: Recursive step - reverse the substring from the second character onwards and append the first character
String reversedString = reverseWithRecursion(str.substring(1)) + str.charAt(0);
return reversedString;
}
public static void main(String[] args) {
// Step 1: Input string
String input = "Hello, world!";
// Step 2: Print the original string
System.out.println("Original: " + input); // Step 3: Reverse the string using StringBuilder and print the result
System.out.println("Reversed with StringBuilder: " + reverseWithStringBuilder(input));
// Step 4: Reverse the string using char array and print the result
System.out.println("Reversed with char array: " + reverseWithCharArray(input));
// Step 5: Reverse the string using recursion and print the result
System.out.println("Reversed with recursion: " + reverseWithRecursion(input));
}
}
Output:
Original: Hello, world!
Reversed with StringBuilder: !dlrow ,olleH
Reversed with char array: !dlrow ,olleH
Reversed with recursion: !dlrow ,olleH
Example 2:
Filename: StringReversalExample.java
public class StringReversalExample {
// Approach 1: Using StringBuilder
public static String reverseWithStringBuilder(String str) {
// Create a StringBuilder object with the input string
StringBuilder stringBuilder = new StringBuilder(str);
// Use the reverse() method of StringBuilder to reverse the string
stringBuilder.reverse();
// Convert the reversed StringBuilder object back to a string and return it
return stringBuilder.toString();
}
// Approach 2: Using a char array
public static String reverseWithCharArray(String str) {
// Convert the input string to a char array
char[] charArray = str.toCharArray();
// Initialize two pointers, one pointing to the start of the char array and the other to the end
int start = 0;
int end = str.length() - 1;
// Iterate until the two pointers meet in the middle
while (start < end) {
// Swap the characters at the start and end positions
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
start++;
end--;
}
// Convert the reversed char array back to a string and return it
return new String(charArray);
}
// Approach 3: Using recursion
public static String reverseWithRecursion(String str) {
// Base case: if the input string is empty, return it
if (str.isEmpty()) {
return str;
}
// Recursive step: reverse the substring starting from the second character and concatenate the first character
return reverseWithRecursion(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
// Input string
String input = "Java Programming";
// Print the original string
System.out.println("Original: " + input);
// Reverse the string using StringBuilder and print the result
System.out.println("Reversed with StringBuilder: " + reverseWithStringBuilder(input));
// Reverse the string using char array and print the result
System.out.println("Reversed with char array: " + reverseWithCharArray(input));
// Reverse the string using recursion and print the result
System.out.println("Reversed with recursion: " + reverseWithRecursion(input));
}
}
Output:
Original: Java Programming
Reversed with StringBuilder: gnimmargorP avaJ
Reversed with char array: gnimmargorP avaJ
Reversed with recursion: gnimmargorP avaJ
Reverse String in Java MCQ
- What is the time complexity of reversing a string using recursion in Java?
- O(n)
- O(log n)
- O(n^2)
- O(2^n)
Explanation: Reversing a string using recursion typically has a time complexity of O(n), where n is the length of the string.
- In Java, which data structure can be used to reverse a string without using any built-in methods?
- Stack
- Queue
- LinkedList
- TreeMap
Explanation: Using a stack, you can push each character of the string onto the stack and then pop them to reverse the string.
- What is the output of reversing the string "Java is fun" using StringBuilder's reverse method?
- Java is fun
- nuf si avaJ
- nuf si Java
- fun is Java
Explanation: StringBuilder's reverse method reverses the characters of the string "Java is fun".
- Which of the following methods is NOT suitable for reversing a string in-place?
- Recursion
- Iteration
- StringBuilder's reverse method
- StringBuffer's reverse method
Explanation: StringBuilder's reverse method returns a new reversed string, it doesn't reverse the string in-place.
- What is the benefit of using recursion for reversing a string in Java?
- Recursion consumes less memory compared to other methods.
- Recursion is faster than iterative methods.
- Recursion allows for easy parallelization.
- Recursion simplifies the code and improves readability.
Recursion offers an elegant and compact method for reversing a string, leading to enhanced code clarity and sustainability.