Answer:
// importing the necessary libraries
import java.util.Scanner;
public class BackwardString {
public static void main(String[] args) {
String input;
// Scanner object to read string from user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter String here : ");
input=scanner.next();
// calling backward method to reverse passed string
backward(input);
// closing Scanner object
scanner.close();
}
// Method to Reverse the input string
private static void backward(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
System.out.println("Reversed String : "+dest);
}
}
Explanation:
// importing the necessary libraries
import java.util.Scanner;
public class BackwardString {
public static void main(String[] args) {
String input;
// Scanner object to read string from user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter String here : ");
input=scanner.next();
// calling backward method to reverse passed string
backward(input);
// closing Scanner object
scanner.close();
}
// Method to Reverse the input string
private static void backward(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
System.out.println("Reversed String : "+dest);
}
}
The program above accepts a String object as an argument and displays its contents backward.
It reverses the any string inputed while producing the output.