Wednesday, 11 October 2017

Reverse a String in Java - Java API

Reverse a string using java existing api is really very easy. Below example will show you how to reverse the string using StringBuilder class.


package com.javadevelopersguide.www;
/**
 * This example will help you to reverse a string using StringBuilder.
 *
 * @author manojkumar.bardhan
 *
 */
public class ReverseString {
/**
* @param args
*/
public static void main(String[] args) {
String inputString = "javadevelopersguide";
System.out.println("Before Reverse::" + inputString);
//You can do this using StringBuffer also, based on your requirement. If you really worried about thread saftey
StringBuilder builder = new StringBuilder(inputString).reverse();
// After Reverse using StringBuilder
inputString = builder.toString();
System.out.println("After Reverse:: " + inputString);
}
}


Output :-

Before Reverse::javadevelopersguide
After Reverse:: ediugsrepolevedavaj


Hope it will help you.