ADVERTISEMENT
ADVERTISEMENT

Java program to Reverse a String

Java program to Reverse String: This an example of Java string programs, In this program we will read a string and reverses the string into another string variable.

Reverse String Example using Java Program

//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);
    }
}

Output

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

Using function/Method

//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);
    }
}

Core Java Example Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.