How to reverse a String in Java



Problem Description

How to reverse a String?

Solution

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.

public class StringReverseExample{
   public static void main(String[] args) {
      String string = "abcdef";
      String reverse = new StringBuffer(string).reverse().toString();
      System.out.println("\nString before reverse: "+string);
      System.out.println("String after reverse: "+reverse);
   }
}

Result

The above code sample will produce the following result.

String before reverse:abcdef
String after reverse:fedcba

Example

Following another example shows how to reverse a String after taking it from command line argument

import java.io.*;
import java.util.*;

public class HelloWorld {
   public static void main(String[] args) {
      String input = "tutorialspoint";
      char[] try1 = input.toCharArray();
      for (int i = try1.length-1;i >= 0; i--) System.out.print(try1[i]);
   }
}

The above code sample will produce the following result.

tniopslairotut 
java_strings.htm
Advertisements