226k views
2 votes
Write a Java method that will take a string and reverse it. Can you come up with a method that is faster than regular reversing of the for loop? [10 points] Example #1: Input: ‘Hello World’ Output: ‘dlroW olleH’

1 Answer

5 votes

Answer:

The program to this question as follows:

Program:

import java.util.*; //import package

class Main //defining class Main

{

public static void main(String[] as) //defining main method

{

String input_string, input; //defining string variables

Scanner obz=new Scanner(System.in); //creating scanner class object

System.out.println("Input the string value: "); //print message

input_string=obz.nextLine(); //input value by user

input=new StringBuffer(input_string).reverse().toString(); //creating instance variable with using reverse method

System.out.print(input);//print value

}

}

Output:

Input the string value:

Hello World

dlroW olleH

Explanation:

In the above program code, a class Main is defined, inside this class-main function is declared, inside this function two string variable "input_string and input" are defined, in which the "input_string" variable is used to take input from the user side.

  • The input variable used as an instance variable, that uses StringBuffer, reverse, and toString method.
  • The StringBuffer accepts the "input_string" variable as parameter and toString, reverse method is used to convert all value into a string and reverse method convert value in reverse order. In the last, the print function is used that print input variable value.
User Andrey Chaschev
by
4.6k points