In: Computer Science
Write a method that accepts a String object as an argument and
displays its contents backward. For instance, if the string
argument is "gravity" the method should display
"ytivarg". Demonstrate the method in a program that asks
the user to input a string and then prints out the result of
passing the string into the method.
Sample Run
java BackwardString
Enter·a·string:Hello·world↵
dlrow·olleH↵
import java.util.*;
public class Main
{
public static void reverse(String str){
String reverse="";
int len = str.length();
for (int i = len-1 ; i >= 0 ; i--)
reverse = reverse + str.charAt(i);
System.out.println("Reverse of the string: " + reverse);
}
public static void main(String args[])
{
String str;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
str = input.nextLine();
reverse(str);
}
}