How to reverse a given String in Java


Learn how to reverse the given inputs in JAVA. Previous post will explain how to revers the given number

The Below Post Will Explain You how to Reverse the Given String By a user. 

importjava.io.DataInputStream; 
public class stringrev {
       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub
              try
              {
                     String name; //Declaring A variable

                     System.out.println(“Enter Your name”); //Just an Statement To print

                     DataInputStream ds = newDataInputStream(System.in);

                     name = ds.readLine(); //Getting input to the variable name.

                     StringBuffer as = new StringBuffer(name);

//passing given string to the Stringbuffer class.

                     as.reverse();//Reversing the given string

                     System.out.println(“The Reversed String is:”+as);

// Displaying Reversed string as output 
              }
              catch(Exception ex)
              {
                  // If you want to show any user defined Error Message You can give here.
              }
       }
}


OutPut:

Enter Your Name:  TechMarket

The Reversed String is: tekraMhceT


I’ve Posted with comments for every line. If this comments make you not comfortable with the post. Please kindly do inform me so that i can avoid those comments in next post.  


Advertisements

Tell us Your Suggestion

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s