, asked
Views : 31

How to reverse String in Java?

I have a Sting in my program I need to reverse this Sting and save it. How can I reverse a Sting in Java? Explain with an example.

2 Answers
Akshaya Akki

StringBuffer class of the java.lang package provides reverse() method. This method returns a reverse sequence of the characters in the current String. Using this method you can reverse a string in Java.

import java.lang.*;
public class StringBufferDemo {
   public static void main(String[] args) {
      StringBuffer buff = new StringBuffer("tutorials point");
      System.out.println("buffer = " + buff);
      
      // reverse characters of the buffer and prints it
      System.out.println("reverse = " + buff.reverse());
      
      // reverse of the buffer is equivalent to the actual buffer
      buff = new StringBuffer("malyalam");
      System.out.println("buffer = " + buff);
      
      // reverse characters of the buffer and prints it
      System.out.println("reverse = " + buff.reverse());
   }
}

Output:

buffer = tutorials point
reverse = tniop slairotut
buffer = malayalam
reverse = malayalam

Ayyan

Following example shows how to reverse a String after taking it from command line argument. The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method.

Example:

public class Sample {
   public static void main(String args[]){
      String str = new String("Hello how are you");
      StringBuffer sb = new StringBuffer(str);
      String str2 = sb.reverse().toString();
      System.out.println(str2);
   }
}

Output:

uoy era woh olleH

Advertisements
Related Questions