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↵
I have created a java application named BackwardString in NetBeans IDE.
package backwardstring;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class BackwardString {
public static String reverse(String s){
//convert the string into charater array
char[] arr1 = s.toCharArray();
//declare array to store the reversed character
char[] arr2 = new char[arr1.length];
int j = 0;
//loop start from last charater in arr1 and store it in first position in arr2
//store all element of arr1 from last into arr2 from starting
for (int i = arr1.length - 1; i >= 0; i--){
arr2[j] = arr1[i];
j++;
}
//convert the character array to string and store it in a result
String result = String.valueOf(arr2);
//return result
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str, rev;
//prompts user to enter string
System.out.print("Enter a string:");
str = sc.nextLine();
//call reverse method and store the result in rev
rev = reverse(str);
//print rev
System.out.println(rev);
}
}
OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.