Java67 - Java Program Example Tutorial Blog
Java Tutorial Example program tips homework assignment solution, interview question answers

eclipse debugging unix linux sql xml blog

SATURDAY, DECEMBER 8, 2012


How to reverse String in Java with or without StringBuffer
Example
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 andStringBuilder to reverse contents of String and then we wrote our own logic to reverse
String. This usestoCharArray() 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
        //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 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
String matches examples in Java
Difference between String and StringBuffer in Java
Best way to convert numbers to String in Java
Difference between == and equals method in Java
How to create Enum from String in Java
How to use contains and indexOf method in String Java
You might like:
How to format Date in Java - SimpleDateFormat Example | Java67 - Java Program Example Tutorial Blog




JDOM Example : Reading and Parsing XML with SAX parser in Java | Java67 - Java Program Example Tutorial
Blog




10 points about Object in Java and Object oriented programming language | Java67 - Java Program Example
Tutorial Blog




Java Interview Questions for 2 to 3 years experience - Answered | Java67 - Java Program Example Tutorial Blog
[?]
Posted by Javin Paul at 3:04 AM
Email ThisBlogThis!Share to TwitterShare to Facebook
Labels: coding, core java, core java interview question answer, programming


1 comment:
             1.
                       RakeshJanuary 8, 2013 at 11:09 PM

                       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.
                       Reply
                                               Newer PostOlder PostHome
Subscribe to: Post Comments (Atom)

                                                                  2
JAVA67 HEADLINE ANIMATOR




                                                 ↑ Grab this Headline Animator

RECENT POSTS WIDGET

FOLLOWERS

BLOG ARCHIVE
► 2013 (9)
    ▼ 2012 (137)
o   ▼ December (26)
   How Constructor Chaining works in Java - Example
   Producer Consumer Problem with Wait and Notify Exa...
   What is public private protected and package or de...
   10 points about Object in Java and Object oriented...
   Difference between ArrayList vs LinkedList in Java...
   How to display date in multiple timezone in Java w...
   How to remove element from Array in Java with Exam...
   How to convert java.sql.Date to java.util.Date in ...
   JDBC Interview questions answers in Java - 2 to 4 ...
   How to check leap year in Java - program example
   Unix command to find IP address from hostname - Li...
   How to run Java program from jar file in command l...
   Difference between RuntimeException and checked Ex...
   Difference between GenericServlet vs HttpServlet i...
   Bubble sort in Java - program to sort integer arra...
   Difference between Array vs ArrayList in Java
   How to remove all white space from String in Java ...
   trustStore vs keyStore in Java SSL
   How to convert String from lowercase to uppercase ...
   NoClassDefFoundError vs ClassNotFoundExcepiton in ...
   Main method Interview Questions in Java - FAQ
   How to read user input from Console in Java using ...
   How to reverse String in Java with or without Stri...
   Difference between Error vs Exception in Java - In...
   How to create and initialize List or ArrayList in ...
   What is difference between Thread vs Process in Ja...
o   ► November (8)
o   ► October (28)
o   ► September (26)
o   ► August (42)
o   ► July (7)

    Jobs
    Senior Software Engineer
    Bangalore, India
    SuccessFactors
    $1,000 Referral Reward
Senior Software Engineer UI
Bangalore, India
SuccessFactors
$1,000 Referral Reward
Software Engineering Intern
Bangalore, India
SuccessFactors
$1,000 Referral Reward
PHP Web Developer / Programmer
Las Vegas, NV
Doppler Internet
Manager Resourcing
Sunnyvale, CA
TruGlobal
POST A JOB >
                                        POWERED BY JOBTHREAD




                                 Simple template. Powered by Blogger.

Java67

  • 1.
    Java67 - JavaProgram Example Tutorial Blog Java Tutorial Example program tips homework assignment solution, interview question answers eclipse debugging unix linux sql xml blog SATURDAY, DECEMBER 8, 2012 How to reverse String in Java with or without StringBuffer Example 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 andStringBuilder to reverse contents of String and then we wrote our own logic to reverse String. This usestoCharArray() 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[]) {
  • 2.
    //quick wasy toreverse 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 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 String matches examples in Java Difference between String and StringBuffer in Java Best way to convert numbers to String in Java Difference between == and equals method in Java How to create Enum from String in Java How to use contains and indexOf method in String Java You might like:
  • 3.
    How to formatDate in Java - SimpleDateFormat Example | Java67 - Java Program Example Tutorial Blog JDOM Example : Reading and Parsing XML with SAX parser in Java | Java67 - Java Program Example Tutorial Blog 10 points about Object in Java and Object oriented programming language | Java67 - Java Program Example Tutorial Blog Java Interview Questions for 2 to 3 years experience - Answered | Java67 - Java Program Example Tutorial Blog
  • 4.
    [?] Posted by JavinPaul at 3:04 AM Email ThisBlogThis!Share to TwitterShare to Facebook Labels: coding, core java, core java interview question answer, programming 1 comment: 1. RakeshJanuary 8, 2013 at 11:09 PM 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. Reply Newer PostOlder PostHome Subscribe to: Post Comments (Atom) 2 JAVA67 HEADLINE ANIMATOR ↑ Grab this Headline Animator RECENT POSTS WIDGET FOLLOWERS BLOG ARCHIVE
  • 5.
    ► 2013 (9) ▼ 2012 (137) o ▼ December (26)  How Constructor Chaining works in Java - Example  Producer Consumer Problem with Wait and Notify Exa...  What is public private protected and package or de...  10 points about Object in Java and Object oriented...  Difference between ArrayList vs LinkedList in Java...  How to display date in multiple timezone in Java w...  How to remove element from Array in Java with Exam...  How to convert java.sql.Date to java.util.Date in ...  JDBC Interview questions answers in Java - 2 to 4 ...  How to check leap year in Java - program example  Unix command to find IP address from hostname - Li...  How to run Java program from jar file in command l...  Difference between RuntimeException and checked Ex...  Difference between GenericServlet vs HttpServlet i...  Bubble sort in Java - program to sort integer arra...  Difference between Array vs ArrayList in Java  How to remove all white space from String in Java ...  trustStore vs keyStore in Java SSL  How to convert String from lowercase to uppercase ...  NoClassDefFoundError vs ClassNotFoundExcepiton in ...  Main method Interview Questions in Java - FAQ  How to read user input from Console in Java using ...  How to reverse String in Java with or without Stri...  Difference between Error vs Exception in Java - In...  How to create and initialize List or ArrayList in ...  What is difference between Thread vs Process in Ja... o ► November (8) o ► October (28) o ► September (26) o ► August (42) o ► July (7) Jobs Senior Software Engineer Bangalore, India SuccessFactors $1,000 Referral Reward
  • 6.
    Senior Software EngineerUI Bangalore, India SuccessFactors $1,000 Referral Reward Software Engineering Intern Bangalore, India SuccessFactors $1,000 Referral Reward PHP Web Developer / Programmer Las Vegas, NV Doppler Internet Manager Resourcing Sunnyvale, CA TruGlobal POST A JOB > POWERED BY JOBTHREAD Simple template. Powered by Blogger.