Sunday, September 4, 2016

Java Program on String Reverse

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

Bhanu Namikaze

Author & Editor

Bhanu Namikaze is an Ethical Hacker, Passionate Blogger, Web Developer, Student and Mechanical Engineer. He Enjoys writing articles, Blogging, Solving Errors, Surfing and Social Networking. Feel Free To Contact Me @ Bhanu.

0 comments:

Post a Comment

Popular Posts

Copyrights @ Interview Questions.Me - Blogger Templates Designed by Templateism - Distributed By Protemplateslab

  • (91) 5544 654942
  • Bhanu@HackingDream.net
  • Interview Questions

Copyrights @ Interview Questions.Me -A Site By Bhanu In Association With Hacking Dream