How to reverse a string in Java? I have a string Hello World" stored in a variable and need to print it in reverse. I heard that Java provides built-in methods for this. What is the best way to java reverse string efficiently? Additionally, how can I reverse each individual word in “Hello World” separately using Java?
From my experience, the easiest and most efficient way to perform a java reverse string operation is by using StringBuilder. Java has a built-in reverse()
method in StringBuilder, and it’s optimized for performance, making it much faster than string concatenation in a loop. You don’t even have to implement anything manually!
String str = "Hello World";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: "dlroW olleH"
This is my go-to solution for most cases, especially since it handles string manipulation efficiently. If you’re working with large datasets or high-performance scenarios, you’ll appreciate this."
Totally agree, @richaaroy That StringBuilder approach is great. But if you’re like me and prefer not to rely on built-in methods for certain tasks, you can also manually reverse the string using a character array and a loop. Here’s how I usually do it:
public static String reverseString(String str) {
char[] charArray = str.toCharArray();
int left = 0, right = charArray.length - 1;
while (left < right) {
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
left++;
right--;
}
return new String(charArray);
}
String str = "Hello World";
System.out.println(reverseString(str)); // Output: "dlroW olleH"
I like this method because it gives you full control over the java reverse string process and avoids unnecessary object creation, making it more efficient. It’s a good option if you’re working in interview scenarios, where you might be asked to do it manually.
Nice suggestions, guys! Now, what if the task is a bit different? Let’s say you want to reverse each word in a sentence, but not the entire string. That’s a fun variation of java reverse string. You can split the string by spaces, reverse each word individually, and then reassemble it. Here’s how I’d do that:
public static String reverseEachWord(String str) {
String[] words = str.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(new StringBuilder(word).reverse().toString()).append(" ");
}
return result.toString().trim();
}
String str = "Hello World";
System.out.println(reverseEachWord(str)); // Output: "olleH dlroW"
This approach is especially useful if you’re dealing with text formatting, natural language processing, or just need to reverse words without changing their order. It’s another great technique when you’re working with string manipulation in Java!