java code to reverse a string


Steps

  1. Select Java form the categories and Java Application  from the projects, click Next.
  2. Set the Project name as reverseString and set the Create Main Class, click Finish.
  3. Under the  project "reverseString", you can see two files, double click the Source Packages,you can see a package by name "reversestring" ,double click it you will find the Java Main Class FileReverseString.java.
  4. Open this file, remove the existing code and  paste the following code.
----------------------------------------------ReverseString.java-------------------------------------------------


package reversestring;
import java.util.*;
/**
 *
 * @author ZISSAN
 */
public class ReverseString {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
//      step.1.  initialize the two string.original will hold the input and reverse(set with a null value)
//               will hold the output 
        String original, reverse ="";
//      step.2.  initialization of the Scanner class,handles input from user,can be found in the java.util.*; library.       
      Scanner in = new Scanner(System.in);
//       step.3. we are creating object "in" from the scanner and telling java that this will be System input
      System.out.println("Enter a string to reverse::");
      original = in.nextLine();
// next() is a method which  gets the next string of text that a user types on the keyboard
      int length = original.length();
      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);
      System.out.println("Reverse of entered string ::"+reverse);// prints the required output
   
    }
}
--------------------------------------------------------output-----------------------------------------------------------------

run:
Enter a string to reverse::
reverse
Reverse of entered string :: esrever
BUILD SUCCESSFUL (total time: 9 seconds)

No comments:

Post a Comment