Reverse String in Java
There are many ways to reverse String in Java. You can use rich Java API
to quickly reverse contents of any String object. Java library provides StringBuffer
and StringBuilder class with 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 most easy way available to reverse String in Java. At the same
time Writing Java program to reverse String in Java without StringBuffer is one
of the popular Java
String interview question, 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 loop to reverse String in Java. In this Java
tutorial I have shown How to reverse String using StringBuffer, StringBuilder
and using pure loop with logic. You can also check How
to reverse String with recursion in Java, if you want to see recursive
code. let's see complete Java program for this beautiful Java programming
exercise.
Java program to reverse String in Java
Here is my complete code program to reverse any String in Java. In main
method we have first used StringBuffer and StringBuilder to reverse contents of String and then we
wrote our own logic to reverse String. This uses toCharArray() method of
String class which return character
array of String. By looping through character array and appending it into
empty String we can get reversed String in Java, as shown in following example.
/**
*
* 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 return 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
*
* 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 return 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
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 library and suggest any one to use StringBuffer or StringBuilder to reverse
String for any production use. Though its also a good
programming exercise and you should practice it before going for any Java
programming interview.
Other Java tutorials you may like
Indeed it's commonly asked to write a Java program to reverse String in Java without using reverse function and it's not EASY. first of all reverse can have different meaning e.g. reverse word by word or reverse each character, preserving whitespace etc. They may ask you to use recursion to write reverse String function instead of using for loop. Best way is to prepare well with all kinds of String related question.
ReplyDeletepublic class ReverseString {
Deleteprivate static String hello = "Hello World";
public static void main(String[] args)
{
System.out.println(reverseString(hello));
}
public static String reverseString(String s) {
char c[] = s.toCharArray();
int i = 0, j = c.length - 1;
while (i < j) {
char tmp = c[i];
c[i] = c[j];
c[j] = tmp;
i++;
j--;
}
return new String(c);
}
Thanks for your answer dude ...Your answer helped me more than the bloggers answer
DeleteNice1
DeletePerfect Dear, Thanks A lot
Deleteclass reverse2
Delete{
public static void main(String args[])
{
String name="rishi thakur";
char[] c=name.toCharArray();
for(int i=c.length-1;i>=0;i--)
{
System.out.print(c[i]);
}
System.out.println();
}
}
But you didn't converted the character array back to string
DeleteAnother solution:
ReplyDeletepublic static String reverse(String s) {
if(s.length() == 1){
return s;
}
else{
return s.charAt(s.length()-1)+reverse(s.substring(1, s.length()-1))+s.charAt(0);
}
}
lie i want to reverse the string like swap between the numbers
Deletelike
input.abcd
output i want was.ba dc
you can find different ways @ http://javacracker.com/different-ways-to-reverse-a-string/
ReplyDeleteBut,the method isEmpty() is undefined for the type String
ReplyDeleteinput= HELLO WORLD
ReplyDeleteoutput= OLLEH DLROW
how will get this output without using any inbuild function??
plz provide me solusn
you can split the string in two strings via locating the space, then reverse them and output
DeleteString S= "Hello World";
DeleteString[] SP = S.split(" ");
for(int i=SP.length-1;i>=0;i--){
System.out.println(SP[i]);
}
}
Above code will throw java.lang.StringIndexOutOfBoundsException
Deleteif the number of characters in the string is even.
Although it will work perfectly in case of odd number of characters.
It won't cause any null pointer exception.
Deletewhy you making people fools you, haven't uses the reverse method at all.......,because if you comment the whole reverse method defined below still you are going to get the
ReplyDeleteanswer
int length=as.length();
ReplyDeleteString reverse="";
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + as.charAt(i);
result.setText(reverse);
**Cannot invoke setText(String) on the primitive type int
Deletewhat should I do?
public class REVERSE {
ReplyDeleteString abc = "Hello World i should be reversed";
void reverse(){
char[] rev =abc.toCharArray();
for(int i =abc.length()-1 ;i>=0;i--){
System.out.print(rev[i]);
}
System.out.println("\n");
}
void wordrevese() {
String [] Tok = abc.split(" ");
for(int k = Tok.length-1 ;k>=0;k--){
System.out.print(Tok[k]+" ");
}
}
public static void main(String[] args){
REVERSE RV = new REVERSE();
RV.reverse();
RV.wordrevese();
}
}
Using reverse very easy for us...
ReplyDeletepublic static void main(String[] args) {
System.out.println("Enter the String...");
Scanner scan=new Scanner(System.in);
String x = scan.next();
StringBuffer sb=new StringBuffer(x);
System.out.println(sb.reverse());
}
it will not execute
DeleteAnother Program:
ReplyDeletepublic class ReverseString {
public String reverseString(String str) {
if (str.length() == 1) {
return str;
}
String reverse="";
reverse += str.charAt(str.length() - 1)
+ reverseString(str.substring(0, str.length() - 1));
return reverse;
}
public static void main(String a[]) {
ReverseString srr = new ReverseString();
System.out.println("Result: " + srr.reverseString("Java Programming"));
}
}
how about
ReplyDeleteinput:dear god
output:god dear
String S= "dear god";
DeleteString[] SP = S.split(" ");
for(int i=SP.length-1;i>=0;i--){
System.out.print(SP[i]+" ");
}
why we write like this String reverse="";why it shows error i can write String reverse;
ReplyDelete@Arun, there you are initializing String variable reverse with empty String.
Deletehow to find String both i.e.Reverse and Palindrome
ReplyDelete@Avinash, if you want to check if String is palindrome or not using recursion then check this solution
Deleteclass mainclass1
ReplyDelete{
public static void main(String[] args)
{
System.out.println("program started");
String str="sun rises in the east";
char[] arr=str.toCharArray();
for (int i=arr.length-1;i>=0 ; i--)
{
System.out.print(arr[i]);
}
}
}
is this acceptable?
ReplyDeleteScanner in = new Scanner(System.in);
System.out.print("Enter String: ");
input = in.nextLine();
//string input converting to array each letter
char inputArr[] = input.toCharArray();
System.out.print("Original String: "+ input + "\nReversed String: ")
//displaying the reverse state of the string
for(int i = input.length(); i > 0 ;--i)
{
System.out.print(inputArr[i-1]);
}
//TODO: Reverse of String
ReplyDeletepublic class ReverseString {
//Without using stringBuffer
public static void StringReverse(String str){
String rev="";
String rev2="";
String rev3="";
System.out.println("#########BY USING STRING CLASS##########\n");
/*TODO: Method 1 : a) Covert the String toCharArray it returns the array character..
* b) Then concatenate them
*/
System.out.println("######BY USING METHOD 1#######");
char chararra[]= str.toCharArray();
for(int i=chararra.length - 1;i>=0;i--){
rev= rev + chararra[i];
}
System.out.println("Result From method 1: "+rev);
/*TODO: Method 2 : a) Split The String into tokens and,
* b) Then concatenate them
*/
System.out.println("######BY USING METHOD 2#######");
String tokens[]= str.split("");
for(int i=tokens.length-1;i >= 0;i--){
rev2 = rev2+tokens[i];
}
System.out.println("Result From method 2: "+rev2);
/*TODO: Method 3 : a) calculate the length of string and use charAt(),
* b) Then concatenate them
*/
System.out.println("######BY USING METHOD 3#######");
int length= str.length();
for(int i=length-1;i>=0;i--){
rev3 = rev3+str.charAt(i);
}
System.out.println("Result From method 3: "+rev3);
}
//TODO: By Using StringBuffer..
public static void StringBuffer(String str){
StringBuffer stringbuff = new StringBuffer(str);
System.out.println();
System.out.println("########## BY USING STRINGBFFER CLASS#######");
System.out.println("\nReverse of String By Using reverse method: "+stringbuff.reverse());
}
}
//Reverse of String By Using String Class and StringBuffer Class
ReplyDeletepublic class ReverseString {
//Without using stringBuffer
public static void StringReverse(String str){
String rev="";
String rev2="";
String rev3="";
System.out.println("#########BY USING STRING CLASS##########\n");
/*TODO: Method 1 : a) Covert the String toCharArray it returns the array character..
* b) Then concatenate them
*/
System.out.println("######BY USING METHOD 1#######");
char chararra[]= str.toCharArray();
for(int i=chararra.length - 1;i>=0;i--){
rev= rev + chararra[i];
}
System.out.println("Result From method 1: "+rev);
/*TODO: Method 2 : a) Split The String into tokens and,
* b) Then concatenate them
*/
System.out.println("######BY USING METHOD 2#######");
String tokens[]= str.split("");
for(int i=tokens.length-1;i >= 0;i--){
rev2 = rev2+tokens[i];
}
System.out.println("Result From method 2: "+rev2);
/*TODO: Method 3 : a) calculate the length of string and use charAt(),
* b) Then concatenate them
*/
System.out.println("######BY USING METHOD 3#######");
int length= str.length();
for(int i=length-1;i>=0;i--){
rev3 = rev3+str.charAt(i);
}
System.out.println("Result From method 3: "+rev3);
}
//TODO: By Using StringBuffer..
public static void StringBuffer(String str){
StringBuffer stringbuff = new StringBuffer(str);
System.out.println();
System.out.println("########## BY USING STRINGBFFER CLASS#######");
System.out.println("\nReverse of String By Using reverse method: "+stringbuff.reverse());
}
}
Hello Zakir, thank for solution but can you also explain the key advantages, algorithm, big O complexity and how it is better from original solution?
DeleteHow to reverse this string "what about you" to "you about what"
ReplyDelete@Pyrathyusha, that's called reversing order of words in String, you can check my solution here
DeleteReverse string without using any library function.
ReplyDelete@Abhishek, check out the below answer by @Asad, if you wan to learn more you can also see here
Deletereverse a string with
ReplyDeleteout using library function is here,,,,
import java.lang.String;
public class MainPagalHoon {
public static void main(String[] args) {
String words[]={"tum","kon","piyaa","ye","main","hoon"};
String reverse= "";
int length=words.length;
for(int i=0;i=0;j--)
{
reverse=reverse+word.charAt(j);
}
reverse=reverse+" ";
}
System.out.println(reverse);
}
}
@Asad, good job, can you convert this algorithm to recursive one as well?
DeleteIs this too simple?
ReplyDelete//---------------
public static String reversemystring(String mystring) {
String myreversestring = "";
for (int i = 0; i <= mystring.length() -1 ; i++) {
myreversestring = mystring.charAt(i) + myreversestring;
}
return myreversestring;
}
//-------------
System.out.println(reversemystring(yourstringtoreverse));
@Anonymous, good solution but it is actually using StringBuilder internally. The String concatenation using + operator internally uses StringBuffer or StringBuilder depending upon whether you are running on Java 1.5 or prior version.
DeleteThis my solution. I think this one is efficient. Please let me know.
ReplyDeletepublic static void main(String[] args)
{
String s = "abcdcba";
int half = s.length()/2,count=0;
for(int i=0,j=s.length()-1;i<half;i++,j--)
{
if(s.charAt(i) == s.charAt(j))
{
count++;
}
}
if(count == half)
{
System.out.println("String is palindrome");
}
else
{
System.out.println("String is not a palindrome");
}
}
Hello Sushil, good solution. But, Can you explain why it is more efficient and will it work for null, empty String or String with both even and odd length?
Deleteprivate static String reverse(String s) {
ReplyDeleteif (s.length() == 0) {
return s;
}
return reverse(s.substring(1)) + s.charAt(0);
}
i want code for
ReplyDeleteIf case_option = 1, Reversal of words with retaining position’s Case
i.e. If the original sentence is “Wipro TechNologies BangaLore”,
the new reversed sentence should be “Orpiw SeigOlonhcet ErolaGnab”
Note that positions 1, 7, 11, 20 and 25 in the original string are uppercase W, T and B.
Similarly positions 1, 7, 11, 20 and 25 in the new string are uppercase O, S, O, E and G
You should be using StringBuilder inside the reverse method... the way you're doing it is very costly if the String is long (you create a new String every iteration). If the point of your demonstration was to avoid using StringBuilder, then you should be using a char array.
ReplyDelete