×

Java Programs

Java Practice

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


    me@linux:~$ javac ReverseString.java 
    me@linux:~$ 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 »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.