How to Reverse String in Java with or without StringBuffer Example (original) (raw)
Reverse String in Java
There are many ways to reverse a given String in Java. For example, you can use rich Java API to quickly reverse the contents of any String object. Java library provides StringBuffer and StringBuilder class with the reverse() method which can be used to reverse String in Java. Since converting between String and StringBuffer or StringBuilder is very easy it's the easiest way available to reverse String in Java. But, in a coding interview, you may not be allowed to use the JDK API methods to solve this problem. That's why, writing a Java program to reverse String in Java without StringBuffer is one of the popular Java String interview questions, which requires you to reverse String by applying logic and by not using API methods.
Since reverse is a recursive job, you can use recursion as well as a loop to reverse String in Java. In this Java tutorial, you will learn how to reverse String using StringBuffer, StringBuilder, and using a pure loop with logic.
Btw, if you are preparing for coding interviews then a good knowledge of techniques like Recursion, Dynamic Programming, Greedy Algorithms, and essential data structures like an array, string, linked list, binary tree, stack, queue, etc are very important.
You should put a decent amount of time into brushing these skills before going for any coding interview or taking calls for any telephonic interviews.
If you need resources, I recommend Data Structures and Algorithms: Deep Dive Using Java to brush up your Data structure and algorithms skills. This is a great and very affordable course on Udemy which you can buy for just $10 on Udemy sales which happens every now and then.
Algorithm to Reverse String in Java
Here are the algorithm and codes to reverse a given String in Java without using StringBuffer or any other API methods. The method below shows you how to reverse the String, which you can further reuse to check if the given String is Palindrome or not.
After initial input validation, we are just iterating through String, starting from end to start and generating a reverse String.
If you want to master the art of solving these kinds of coding problems then Grokking the Coding Interview: Patterns for Coding Questions on Educative is an excellent course to join.
This course will teach you how to identify a pattern among different coding problems and use that skill to solve unknown problems that are asked in a coding interview on companies like Google, Amazon, and Microsoft.
Java Program to Reverse String in Java
Here is my complete code program to reverse any String in Java. In the main method, we have first used StringBuffer and StringBuilder to reverse the contents of String, and then we wrote our own logic to reverse String.
This uses the toCharArray() method of String class which returns the character array of String. By looping through the character array and appending it into an empty String we can get a reversed String in Java, as shown in the following example.
You can also check How to reverse String with recursion in Java if you want to see the recursive code. let's see the complete Java program for this beautiful Java programming exercise.
/**
*
* Java program to reverse String in Java.
* There are multiple ways to reverse
* String in Java, you can either take help of standard
* Java API StringBuffer to reverse String in Java.
* StringBuffer has a reverse() method which returns StringBuffer
* with reversed contents.
*
* On the other hand, you can also reverse it by applying your
* own logic, if asked to reverse String without
* using StringBuffer in Java.
*
* By the way you can also use StringBuilder to reverse
* String in Java. StringBuilder is non-thread-safe
* version of StringBuffer and provides similar API.
* You can use StringBuilder's reverse()
* method to reverse content and then convert it back to String
*
* @author http://java67.blogspot.com
*/
public class StringReverseExample {
public static void main(String args[]) {
//quick wasy to reverse String in Java - Use StringBuffer
String word = "HelloWorld";
String reverse = new StringBuffer(word).reverse().toString();
System.out.printf(" original String : %s ,
reversed String %s %n", word, reverse);
//another quick to reverse String in Java - use StringBuilder
word = "WakeUp";
reverse = new StringBuilder(word).reverse().toString();
System.out.printf(" original String : %s ,
reversed String %s %n", word, reverse);
// one way to reverse String without using // StringBuffer or StringBuilder is writing
// own utility method
word = "Band";
reverse = reverse(word);
System.out.printf(" original String : %s ,
reversed String %s %n",
word, reverse);
}
public static String reverse(String source){
if(source == null || source.isEmpty()){
return source;
}
String reverse = "";
for(int i = source.length() -1; i>=0; i--){
reverse = reverse + source.charAt(i);
}
return reverse;
}
}
Output:
original String: HelloWorld, reversed String dlroWolleH
original String: WakeUp, reversed String pUekaW
original String: Band, reversed String dnaB
That's all on How to reverse String in Java with and without StringBuffer and StringBuilder. Though being a Java programmer I prefer to use a library and suggest anyone use StringBuffer or StringBuilder to reverse String for any production use. Though it's also a good programming exercise and you should practice it before going for any Java programming interview.
Other Coding Problems and Programming articles you may like
- How to remove an element from the array without using a third-party library (check here)
- 10 points about array in Java (read here)
- 10 Free Courses to learn Data Structure and Algorithms (courses)
- How to find the largest and smallest number in an array in Java (read here)
- Difference between array and ArrayList in Java (see here)
- How to loop over an array in Java (read here)
- 4 ways to sort array in Java (see here)
- 100+ Data Structure and Algorithms Problems (solved)
- How to convert Array to String in Java (read here)
- 6 Best Dynamic Programming Courses for Interviews (courses)
- How to print array in Java with examples (read here)
- How to declare and initialize a multi-dimensional array in Java (see here)
- How to compare two arrays in Java (check here)
- 10 Books to learn Data Structure and Algorithms (books)
- How to find two maximum numbers on an integer array in Java (check here)
- 7 Best Data Structure and Algorithms courses (online courses)
Thanks for reading this article so far. If you like this String based coding Interview question then please share it with your friends and colleagues. If you have any doubt or feedback then please drop a note.
P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data Structure in Java courses on Udemy. It's completely free, and all you need to do is create a free Udemy account to enroll in this course.
By the way, What is your favorite Java coding exercise? Palindrome, Prime Number, Producer consumer problem , or this one? Do let me know in comments.