How to reverse a string in Java

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Filament.io 0 Flares ×

There are two approaches to reverse a string in java

1) Use the StringBuffer class

StringBuffer provides a reverse method to do the job

[code language=”java”]

public class ReverseString
{
public static void main(String args[])
{
StringBuffer buff = new StringBuffer("Hello World");
System.out.println(buff.reverse());
}
}

2) Use charAt(int i) method of String class

Use the charAt method to extract characters from the string and append in the reverse order to reverse the input string.