Java Program to Reverse a String

You are currently viewing Java Program to Reverse a String

Java Program to Reverse a String

//Java program to Reverse a String.
 
import java.util.*;
 
public class ReverseString
{
    public static void main(String args[]){
        String str;
        String rStr;
        Scanner bf=new Scanner(System.in);
         
        //input an integer number
        System.out.print("Enter any string: ");
        str=bf.nextLine();
         
        //Reversing String
        rStr="";
        for(int loop=str.length()-1; loop>=0; loop--)
            rStr= rStr + str.charAt(loop);
         
        System.out.println("Reversed string is: " + rStr);
    }
}
//Java program to Reverse a String.
 
//Using String.ReverseString
import java.util.*;
 
public class ReverseString
{
    public static void main(String args[]){
        String str;
        String rStr="";
        Scanner bf=new Scanner(System.in);
         
        //input an integer number
        System.out.print("Enter any string: ");
        str=bf.nextLine();
         
        //Reversing String
        StringBuffer a = new StringBuffer(str);
        System.out.println(a.reverse());
         
        //rStr=str.reverse();
         
        System.out.println("Reversed string is: " + rStr);
    }
}

Output


    [email protected]:~$ javac ReverseString.java 
    [email protected]:~$ java ReverseString 
    Enter any string: Hello World!
    Reversed string is: !dlroW olleH

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply