Reverse a String in Java

Reversing a String

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


// 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(;

// 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());



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.

Posted by at on

Tags: String Handling,