Reverses a String as per StringBuffer#reverse() - Java java.lang

Java examples for java.lang:String Algorithm

Description

Reverses a String as per StringBuffer#reverse()

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(reverse(str));
    }/* w w w .  j  av  a  2s .  c  o m*/

    /**
     * <p>Reverses a String as per {@link StringBuffer#reverse()}.</p>
     *
     * <p>A <code>null</code> String returns <code>null</code>.</p>
     *
     * <pre>
     * reverse(null)  = null
     * reverse("")    = ""
     * reverse("bat") = "tab"
     * </pre>
     *
     * @param str  the String to reverse, may be null
     * @return the reversed String, <code>null</code> if null String input
     */
    public static String reverse(String str) {
        if (str == null) {
            return null;
        }
        return new StringBuffer(str).reverse().toString();
    }
}

Related Tutorials