Reverse string program in Java using stringbuffer

Reverse a string in java Program using stringbuffer

Here, we are supposed to create a source code that asks for String input from the user and displays the string in reverse order.

The basic idea is to pass the Input String to StringBuffer class and then invoke the reverse() function from the class using any object declared. Here we are using ‘str’ as the object that invokes reverse( ) function. The same is displayed as a result.

Source Code:

/* Program to enter a string and print it after reversing it.*/

import java.io.*; class RevStringFunc { public static void main()throws IOException { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.print("\n Enter String: "); String s=bf.readLine(); StringBuffer str=new StringBuffer(s); str.reverse(); System.out.println("Reversed String: "+str);

} }

Output:

Enter String: Tony Stark
Reversed String: kratS ynoT

Enter String: Peter Parker Reversed String: rekraP reteP

Reverse string program in Java using stringbuffer