public class StringUtils {
public static String reverseString(String string){
/*
Check if the string is not null and empty
*/
if(string != null && !string.isEmpty()){
/*
Create a StringBuilder from the string in hand
*/
StringBuilder str = new StringBuilder(string);
/*
Reverse the StringBuilder content and return it as a String
*/
return str.reverse().toString();
}
return null;
}
public static void main(String[] args){
System.out.println(StringUtils.reverseString("I am your father"));
}
}
Output is "rehtaf ruoy ma I".
It is possible to use StringBuffer instead of StringBuilder. As I don't need thread safety I'll pick StringBuilder which's faster. Quite easy to reverse a string, right?