1 Backward String Write a method that accepts a String objec
1. Backward String
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 passes it
to the method.
Solution
ReverseString.java
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(\"Enter the string :\");
String str = in.nextLine();
backwardString(str);
}
public static void backwardString(String str){
System.out.println(\"Reverse String is :\");
for(int i=str.length()-1 ; i>=0; i--){
System.out.print(str.charAt(i));
}
}
}
Output:
Enter the string :
gravity
Reverse String is :
ytivarg
