Java program to reverse a String

In this post,  we will see java program to reverse a String.
There are many ways to do it, some of them are:
  • Using for loop
  • Using recursion
  • Using StringBuffer

Using for loop:

class ReverseStringForMain
{
 public static void main(String[] args)
 {
  String blogName="java2blog";
  String reverse="";
  for(int i=blogName.length()-1;i>=0;i--)
  {
   reverse=reverse+blogName.charAt(i);
  }
  System.out.println("Reverse of java2blog is:"+reverse);
 }
}
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj

Using recursion:

class ReverseStringRecursive
{
 public static void main(String[] args)
 {
  ReverseStringRecursive rsr=new ReverseStringRecursive();
  String blogName="java2blog";
  String reverse=rsr.recursiveReverse(blogName);
  System.out.println("Reverse of java2blog is:"+reverse);
 }
 
 public String recursiveReverse(String orig)
 {
  if(orig.length()==1)
   return orig;
  else
   return orig.charAt(orig.length()-1)+recursiveReverse(orig.substring(0,orig.length()-1));
   
  
 }
}
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj

Using StringBuffer:

class ReverseStringRecursive
{
 public static void main(String[] args)
 {
  ReverseStringRecursive rsr=new ReverseStringRecursive();
  String blogName="java2blog";
  StringBuffer sb=new StringBuffer(blogName);
  System.out.println("Reverse of java2blog is:"+sb.reverse());
 }
}
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj

Please go through java interview programs for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012