Published on


Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Java67 - Java Program Example Tutorial BlogJava Tutorial Example program tips homework assignment solution, interview question answerseclipse debugging unix linux sql xml blogSATURDAY, DECEMBER 8, 2012How to reverse String in Java with or without StringBufferExampleReverse String in JavaThere are many ways to reverse String in Java. You can use rich Java API to quickly reverse contents of any Stringobject. Java library provides StringBuffer and StringBuilder class with reverse() method which can beused to reverse String in Java. Since converting between String and StringBuffer or StringBuilder is veryeasy its the most easy way available to reverse String in Java. At the same time Writing Java program to reverseString in Java without StringBuffer is one of the popular Java String interview question, which requires you toreverse String by applying logic and by not using API methods. Since reverse is a recursive job, you can userecursion as well as loop to reverse String in Java. In this Java tutorial I have shown How to reverse String usingStringBuffer, StringBuilder and using pure loop with logic. You can also check How to reverse String withrecursion in Java, if you want to see recursive code. lets see complete Java program for this beautiful Javaprogramming 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 firstused StringBuffer andStringBuilder to reverse contents of String and then we wrote our own logic to reverseString. This usestoCharArray() method of String class which return character array of String. By looping throughcharacter array and appending it into empty String we can get reversed String in Java, as shown in followingexample./** * * 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 returnStringBuffer * 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 theway * you can also use StringBuilder to reverse String in Java. StringBuilder is nonthread-safe * version of StringBuffer and provides similar API. You can use StringBuildersreverse() * method to reverse content and then convert it back to String * * @author */public class StringReverseExample { public static void main(String args[]) {
  2. 2. //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 iswriting //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 dlroWolleHoriginal String : WakeUp , reversed String pUekaWoriginal String : Band , reversed String dnaBThats all on How to reverse String in Java with and without StringBuffer and StringBuilder. Though being aJava programmer I prefer to use library and suggest any one to use StringBuffer or StringBuilder to reverseString for any production use. Though its also a good programming exercise and you should practice it before goingfor any Java programming interview.Other Java tutorials you may likeString matches examples in JavaDifference between String and StringBuffer in JavaBest way to convert numbers to String in JavaDifference between == and equals method in JavaHow to create Enum from String in JavaHow to use contains and indexOf method in String JavaYou might like:
  3. 3. How to format Date in Java - SimpleDateFormat Example | Java67 - Java Program Example Tutorial BlogJDOM Example : Reading and Parsing XML with SAX parser in Java | Java67 - Java Program Example TutorialBlog10 points about Object in Java and Object oriented programming language | Java67 - Java Program ExampleTutorial BlogJava Interview Questions for 2 to 3 years experience - Answered | Java67 - Java Program Example Tutorial Blog
  4. 4. [?]Posted by Javin Paul at 3:04 AMEmail ThisBlogThis!Share to TwitterShare to FacebookLabels: coding, core java, core java interview question answer, programming1 comment: 1. RakeshJanuary 8, 2013 at 11:09 PM Indeed its commonly asked to write a Java program to reverse String in Java without using reverse function and its 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 PostHomeSubscribe to: Post Comments (Atom) 2JAVA67 HEADLINE ANIMATOR ↑ Grab this Headline AnimatorRECENT POSTS WIDGETFOLLOWERSBLOG ARCHIVE
  5. 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. 6. Senior Software Engineer UIBangalore, IndiaSuccessFactors$1,000 Referral RewardSoftware Engineering InternBangalore, IndiaSuccessFactors$1,000 Referral RewardPHP Web Developer / ProgrammerLas Vegas, NVDoppler InternetManager ResourcingSunnyvale, CATruGlobalPOST A JOB > POWERED BY JOBTHREAD Simple template. Powered by Blogger.