SlideShare a Scribd company logo
1 of 6
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.

More Related Content

What's hot

What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About RubyKeith Bennett
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style GuidesMosky Liu
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder RubyNick Sieger
 
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and SparkScala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and SparkEduardo Gonzalez
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noiseNeeraj Bhusare
 
Enhancing VAEs for collaborative filtering : flexible priors & gating mechanisms
Enhancing VAEs for collaborative filtering : flexible priors & gating mechanismsEnhancing VAEs for collaborative filtering : flexible priors & gating mechanisms
Enhancing VAEs for collaborative filtering : flexible priors & gating mechanismsseungwoo kim
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancementmuthusvm
 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 referenceGiacomo Veneri
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Code Generation idioms with Xtend
Code Generation idioms with XtendCode Generation idioms with Xtend
Code Generation idioms with XtendHolger Schill
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 

What's hot (20)

CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
 
Viva file
Viva fileViva file
Viva file
 
What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About Ruby
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
 
Java scriptforjavadev part2a
Java scriptforjavadev part2aJava scriptforjavadev part2a
Java scriptforjavadev part2a
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and SparkScala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Enhancing VAEs for collaborative filtering : flexible priors & gating mechanisms
Enhancing VAEs for collaborative filtering : flexible priors & gating mechanismsEnhancing VAEs for collaborative filtering : flexible priors & gating mechanisms
Enhancing VAEs for collaborative filtering : flexible priors & gating mechanisms
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancement
 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 reference
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Core java
Core javaCore java
Core java
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Code Generation idioms with Xtend
Code Generation idioms with XtendCode Generation idioms with Xtend
Code Generation idioms with Xtend
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 

Similar to Java67

Scala the-good-parts
Scala the-good-partsScala the-good-parts
Scala the-good-partsFuqiang Wang
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PunePankaj kshirsagar
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSujit Majety
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
Basics java programing
Basics java programingBasics java programing
Basics java programingDarshan Gohel
 
Java Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsAkshaj Vadakkath Joshy
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3Vijay Shukla
 

Similar to Java67 (20)

Scala the-good-parts
Scala the-good-partsScala the-good-parts
Scala the-good-parts
 
Interview-QA.pptx
Interview-QA.pptxInterview-QA.pptx
Interview-QA.pptx
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
13 java beans
13 java beans13 java beans
13 java beans
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
 
Java Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming Basics
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Hello java
Hello java  Hello java
Hello java
 
Hello java
Hello java   Hello java
Hello java
 
Hello Java-First Level
Hello Java-First LevelHello Java-First Level
Hello Java-First Level
 
Rjb
RjbRjb
Rjb
 

Recently uploaded

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 

Java67

  • 1. 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[]) {
  • 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 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 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
  • 4. [?] 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
  • 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 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.