Well, while coding in Java or J2EE, you may require to reverse a string and there are few ways to do it, which I am going to explain today, all are easy methods. Before you continue reading this article, I assume you have basic knowledge of Java.

1. Reverse string by converting string into bytes

In this method, we will,

1. Create a temporary byte[] of length equal to the length of the input string.
2. Store the bytes (which we get by using getBytes() method) in reverse order into the temporary byte[] .
3. Create a new String abject using byte[] to store result.

Let's try this in our IDE, I am using Eclipse(oxygen):

// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "qawithexperts";
 
        // getBytes() method to convert string 
        // into bytes[].
        byte [] strAsByteArray = input.getBytes();
 
        //create a new byte array for storing results
        byte [] result = 
                   new byte [strAsByteArray.length];
 
        // Store result in reverse order into the
        // result byte[]
        for (int i = 0; i<strAsByteArray.length; i++)
            result[i] = 
             strAsByteArray[strAsByteArray.length-i-1];
 
        //print the new byte array as string
        System.out.println(new String(result));
    }
}

Output:

strepxehtiwaq

reverse-string-using-java-program.png

You can consider this working online link http://rextester.com/OGR6551

2. Reverse string using subString() and charAt()

In this method we will be using subString() and charAt() functions to reverse the string, basically, we will be:

1. Passing String to function recursively.
2. Removing the first alphabet using subString() and getting first character of the original string
3. Again Calling the method, and use the remaining subString and getting the second character of the original string and so on..

So here is the complete code:

public static void main(String[] args)
    {   	
            String input = "qawithexperts";
            String reversed = reverseString(input);
            System.out.println(reversed);              

    }
    public static String reverseString(String str)
    {
       //at the end if string is empty end recursion
        if (str.isEmpty())
            return str;
        
        
        //Recurive call 
        return reverseString(str.substring(1)) + str.charAt(0);
    }

Output:

strepxehtiwaq

Working example http://rextester.com/ATJ39282

3.Reversing string using Temp variable

In this method, we will create the char[] of the original string first, then loop through each value of array, and append the last value of original string at first of the second string, so basically steps are

  1. Create a char[] of original string and create two ints (begin & end) variable
  2. Swap the characters of the start index scanning with the last index scanning one by one. After that, increase the begin index by 1 (begin++) and decrease the end by 1 i.e., (end--) to move on to the next characters in the character array .
  3. Continue till end is greater than begin.

the complete working code is as below:

class ReverseString
{
    public static void main(String[] args)
    {   	
            String input = "Reversing string using temp variable";
            String reversed = reverse(input);
            System.out.println(reversed);              

    }
    public static String reverse(String input){
        char[] in = input.toCharArray();
        int begin=0;
        int end=in.length-1;
        char temp;
        while(end>begin){
            temp = in[begin];
            in[begin]=in[end];
            in[end] = temp;
            end--;
            begin++;
        }
        return new String(in);
    }
}

Output:

elbairav pmet gnisu gnirts gnisreveR

Working link example http://rextester.com/PHXD45959

4.Using built-in reverse() method of the StringBuilder class

This method requires us to convert the input string(original string) to StringBuilder, which is achieved by using the append method of StringBuilder. After that, print out the characters of the reversed string by scanning from the first till the last index.

public static void main(String[] args)
    {   	
            String input = "Reversing string using stringbuilder variable";
            StringBuilder strBuilder = new StringBuilder();
 
            // append a string into StringBuilder strBuilder
            strBuilder.append(input);

            // reverse StringBuilder input1
            strBuilder = strBuilder.reverse();

            // print reversed String
            for (int i=0; i<strBuilder.length(); i++)
                System.out.print(strBuilder.charAt(i));
    }

output:

elbairav redliubgnirts gnisu gnirts gnisreveR

Working link here : http://rextester.com/LHVA86019

Note: For versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have the same API.

5.Program to reverse a string entered by user

In this , we are not using anything new, we will be using method 2, but this instead of static string, we will ask user to enter string and reverse it, so here is the complete code for it:

import java.util.Scanner;

// Class of ReverseString
class ReverseString
{
	public static void main(String[] args) {
        String str;

        //ask user to enter his/her name
        System.out.println("Enter your name: ");
        
        //create a scanner variable, to get username
        Scanner scanner = new Scanner(System.in);
        //read string entered by user
        str = scanner.nextLine();
        scanner.close();

        //call reverseString method 
        String reversed = reverseString(str);
        System.out.println("Your reversed name is: " + reversed);
    }

    public static String reverseString(String str)
    {
        if (str.isEmpty())
            return str;
        //Calling Function Recursively
        return reverseString(str.substring(1)) + str.charAt(0);
    }

}

Output:

reverse-string-user-entered.png

6. Reverse string by converting it to character array and print last character first

In this method, we will first, convert String to character array by using the built-in Java String class method toCharArray() and then scan the string from end to start, and print the character one by one.

class ReverseString
{
	public static void main(String[] args)
    {
        String input = "qa with experts";
 
        // convert String to character array
        // by using toCharArray
        char[] try1 = input.toCharArray();
 
        for (int i = try1.length-1; i>=0; i--)
            System.out.print(try1[i]);
    }

}

Output:

strepxe htiw aq

Working link here: http://rextester.com/MEX6051

You may also like

Leap year program in Java (multiple ways)

Pyramid Triangle pattern programs in Java with explanation