Explain Codes LogoExplain Codes Logo

Reverse a string in Java

java
string-reversal
coding-interview
best-practices
Alex KataevbyAlex Kataev·Aug 12, 2024
TLDR

For fast and furious string reversal in Java, StringBuilder is your buddy:

String reversed = new StringBuilder("Original").reverse().toString();

Here, we construct a StringBuilder with the original string, cleverly use reverse(), and get the inverted string back with toString(). Effective, efficient, and straightforward.

Options for different Java versions

Java 5 onwards, StringBuilder utilizes less resources, making it faster than StringBuffer. Here's how you can reverse a string:

String reversed = new StringBuilder("Java 5+").reverse().toString();

In versions prior to Java 5, StringBuffer is your friend. Use its reverse() method:

String reversed = new StringBuffer("Pre Java 5").reverse().toString();

Keep in mind that StringBuffer is synchronised and therefore slower than StringBuilder, so use it only when you require thread safety.

Manual reversal for muscle flexing

What if you're at a coding interview and the interviewer forbids the use of StringBuilder or StringBuffer? Don't fret, you can reverse a string manually:

public String reverseManually(String input) { char[] chars = input.toCharArray(); int left = 0; int right = chars.length - 1; while (left < right) { // The ol' switcheroo! 🔄 char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } return new String(chars); }

This method performs the classic act of swapping characters from both ends to middle. Throw it in your coding utility belt!

Reverse for the 'Purist'

Are you a purist, looking to gain the same results with traditional techniques? Well, let's reverse without using reverse():

public String reverseWithStringBuilder(String input) { StringBuilder reversed = new StringBuilder(); for (int i = input.length() - 1; i >= 0; i--) { reversed.append(input.charAt(i)); // Going once... going twice... going thrice... back to front! } return reversed.toString(); }

This method elegantly iterates through the characters backwards, appending them to StringBuilder.

Word-wise reversal for fun and function

Fancy an upside-down world where words are reversed and not the sentences? Voila!

public String reverseWords(String input) { String[] words = input.split(" "); StringBuilder reversed = new StringBuilder(); for (String word : words) { reversed.append(new StringBuilder(word).reverse().toString()).append(" "); } return reversed.toString().trim(); // Clean and tidy with trim(). No trailing spaces here! 🧹 }

This method looks at sentences through a unique lens by splitting words scalarly, reversing them, and stitching them back together.

Beware the Unicode Beast

Unicode and emoji characters are a castle full of hidden passageways; tricky to manipulate. They may not be reversed correctly with basic char-swapping methods. Handle surrogate pairs appropriately if you foresee them in your string.

Additionally, right when you think you've got the treasure, a NullPointerException dragon might spring up if you neglect to check for null or empty string. Saber at the ready!

public String safeReverse(String input) { if (input == null) { return null; // You shall not pass! 🧙 } return new StringBuilder(input).reverse().toString(); }

Still here? Time for real-world applications!

Reversing of strings are not just for showing-off or acing interviews; they have noteworthy applications:

  • Data processing: Goodbye, reverse strings!
  • Security: Shhh! It's our little secret - token obfuscation.
  • Algorithms: Mirror, mirror on the wall, is it a palindrome after all?

Customize your solution keeping the requirements and constraints in mind.