Adsense 728 * 15

Search

Custom Search

Program to Reverse a String in Java

Write a program to reverse a string in Java. In this program we reverse a string with or without using StringBuffer class.

Program to Reverse a String in Java without using StringBuffer Class


import java.util.*;

public class ReverseString {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
         String str, rev = "";
         int len, i;
         
         Scanner inp = new Scanner(System.in);
         
         System.out.println("Enter a string \n");
         
         str = inp.nextLine();
         len = str.length();
         
         for (i = len-1; i >= 0; i--) {
             
             rev = rev + str.charAt(i);
         }
        
         System.out.println("Reverse of a input string is "+ rev);
    }
    
}


Output

Enter a string : cprogrammingcode

Reverse of a input string is : edocgnimmargorpc

Reverse a String in Java using StringBuffer Class


import java.util.*;

public class ReverseString {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
         String str;
         
         Scanner inp = new Scanner(System.in);
         
         System.out.println("Enter a string \n");
         
         str = inp.nextLine();
         
         StringBuffer reverse = new StringBuffer(str);
         reverse.reverse().toString();
        
         System.out.println("Reverse of a input string is "+ reverse);
    }

}

No comments:

Post a Comment