How To Reverse a String in Java

There are a multiple ways to solve a programming problem. There may be library classes that may be very useful in solving programming problems. If you don't know these classes and methods, you will end up  spending time writing your own methods and wasting time. We would use the programming problem of reversing a given String to illustrate this.

If you have a String such as "Hello", the reverse would be "olleH". The logic is easy to find, start from the end of the given string and then take each character till the beginning. Append all these characters to create the reversed String. The following program implements this logic to reverse a given String,

import java.util.Scanner;
/**
 * Reverse a String given by user. Write our own reversing logic 
 */
public class ReverseString1 {
    
    public static void main(String[] args) {
        ReverseString1 rs = new ReverseString1();
        System.out.print("Please enter String to reverse:");
 
        Scanner sn = new Scanner(System.in);
        String input = sn.nextLine();
        String output = rs.reverseString(input);
        System.out.println("The reverse form of "+input+" is "+output);
    }

    /**
     * Our custom method to reverse a string.
     * @param input
     * @return 
     */
    private String reverseString(String input) {
        String reversedString = "";
        char[] characters = input.toCharArray();
        for(int i=characters.length-1;i>=0;i--) {
            reversedString+=characters[i];
        }
        return reversedString;
    }
}

However there is a much easier way to reverse Strings. The StringBuilder class of Java has a built-in reverse method! The following program demonstrates the usage of this library method. This is much better since we can implement it faster and can be sure that the library method is well tested reducing the amount of bugs in your code. This is the approach you should follow when writing Java programs. Always make use of Java library classes or reliable third party libraries to solve your problem.

import java.util.Scanner;
/**
 * Reverse a String given by user using Java library methods
 */
public class ReverseString2 {
    
    public static void main(String[] args) {
        ReverseString1 rs = new ReverseString1();
        System.out.print("Please enter String to reverse:");
 
        Scanner sn = new Scanner(System.in);
        String input = sn.nextLine();
        StringBuffer sb = new StringBuffer(input);
        String output = sb.reverse().toString();
        System.out.println("The reverse form of "+input+" is "+output);
    }
}