ADS

Reverse A String In Java

Reversing a String


An example for reversing a string in Java using reverse() method in StringBuffer with explanation.


Example


// import for java.util.Scanner class
import java.util.*;
class ReverseString
{
public static void main(String args[])
{

// Create Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);

// Read input from the user
String st=s.nextLine();

// Create StringBuffer object for st
StringBuffer sb=new StringBuffer(st);

// Print the reversed string
System.out.println("Reversed String is "+sb.reverse());

}
}

Output


gowtham gutha
Reversed String is ahtug mahtwog
ahtug mahtwog

Tip: Any operation performed on the StringBuffer object is permanent unlike on the String object and that is the difference between String and StringBuffer object.

Subscribe to receive free email updates:

ADS