{{announcement.body}}
{{announcement.title}}

Reverse String Alternatives in Java [Snippets]

DZone 's Guide to

Reverse String Alternatives in Java [Snippets]

Sometimes, you've got to think outside of the box.

· Java Zone ·
Free Resource

Reverse String

Learn more about the various ways you can implement a reverse String in your Java code. 

Recently,  I came across a request to reverse a given string in Java. This does seem a bit odd, but nonetheless, I was asked to perform a reverse without using in-built methods, additional parameters, or any other common way. I am not sure if other companies follow this trend of not using Java API methods, but still, in interviews, companies want you to think beyond what you know and would typically do.

You may also like: The Right Way to Reverse a String in Java

Reversing a string becomes much easier with Java reverse() in the AbstractStringBuilder class method, which takes care of all wired scenarios. 

Let's try out some different ways to reverse a Java string

1. Reverse String Without Using Temp Variable (Recursive)

private String reverseString(String original) {
  if(original.isEmpty())    { 
    return original;    
  }   
 return reverseString(original.substring(1)) + original.charAt(0);
}


Other than the above, below are few more ways to perform a reverse string:

2. Using the Reverse Method

private String reverseString(String original){  
  return new StringBuilder(original).reverse().toString();
}


3. Using RLO Character

private String reverseString(String original){  
  return "\u202E" + original;
}


4. Using the SubString Method

private String reverseString(String str){ 
  // base case: if string is null or empty   
  if (str == null || str.equals(""))      
    return str;  
  // last character + recur for remaining string  
  return str.charAt(str.length() - 1) +          
    reverse(str.substring(0, str.length() - 1));
}


We hope you enjoyed these alternative ways of reversing a string in Java. Happy coding!

Further Reading

The Right Way to Reverse a String in Java

New Methods on Java Strings With JDK 11

Topics:
java ,string

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}