Reversing a string in Java without using StringBuilder or StringBuffer can be accomplished in several ways. Here, I'll explain one approach using character arrays:
Example 1-
public class ReverseString {
public static String reverse(String input) {
// Convert the string to a character array
char[] charArray = input.toCharArray();
// Initialize pointers for start and end of the array
int start = 0;
int end = charArray.length - 1;
// Swap characters from start to end until middle is reached
while (start < end) {
// Swap characters
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
// Move pointers towards the center
start++;
end--;
}
// Convert the character array back to a string
return new String(charArray);
}
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = reverse(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
}
Example 2- Using Recursion
public class ReverseStringRecursive {
public static String reverse(String input) {
// Base case: if the string is empty or has only one character, return it as is
if (input == null || input.length() <= 1) {
return input;
}
// Recursive case: reverse the substring from the second character to the end, and add the first character at the end
return reverse(input.substring(1)) + input.charAt(0);
}
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = reverse(original);
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
}
Example 3- Using a predefined function
import java.util.*;
public class Main {
public static void main(String[] args) {
String original = "Hello, World!";
// Split the string into a list of characters
List<String> characters = Arrays.asList(original.split(""));
// Reverse the list
Collections.reverse(characters);
// Join the reversed list back into a string
String reversed = String.join("", characters);
// Print the original and reversed strings
System.out.println("Original: " + original);
System.out.println("Reversed: " + reversed);
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Reversing a string in Java without using
StringBuilderorStringBuffercan be accomplished in several ways. Here, I'll explain one approach using character arrays:Example 1-
Example 2- Using Recursion
Example 3- Using a predefined function
Read more
Discuss the differences between deep copy and shallow copy in Java objects.
Bitwise AND, OR, XOR, and left/right shift operations.
Explain the 'System.out.println()' and 'System.in'
Product Drag and Drop with Knockout
Form validation and request submission in knockout js