How to reverse a string in Java [4 Methods with Examples]

 

Introduction to reverse a string in Java

In the Java programming language, strings are objects which are a sequence of characters. You can read more about strings and their declaration and syntax from the article Java strings. In this tutorial, we will learn about reverse a string in Java. We will cover various different techniques and methods to reverse a string in java through examples. We will discuss CharAt() method, getBytes(), toCharArray() and reverse() method to reverse a string in java. In the upcoming sections, we will cover each of these methods in detail. To summarize, this tutorial contains all the possible methods which we can use to reverse a string in Java.

 

Getting started with how to reverse a string in Java

Reversing a String in Java is the technique that reverses or changes the order of a given string so that the last character of the string becomes the first character of the string and so on. For example, see the diagram below which shows the reverse of a string when applied different methods of reverse.

Advertisement

reverse a string in java

In the above diagram, you can see that after reversing the string, the very last character becomes the first, the second last become the second, and so on. There are various methods available in java to achieve this goal, and in the upcoming sections, we will discuss some of these methods to reverse a string in java.

 

Method-1: Use charAt() to reverse a string in Java

The Java charAt() method returns a character at a specific index position in a string. The first character in a string has the index position 0. charAt() returns a single character. It does not return a range of characters. We can use this method to reverse a string in java. In this section, we will look at the basic syntax of charAt() method and then will solve an example of reversing a string.

 

Syntax of charAt() method

The built-in Java string charAt() method returns a character at a particular index position in a string. The first character has the index value 0 and so on for subsequent characters in the string. The simple syntax of charAt() method looks like this:

char VariableName = StringName.charAt(Position);

Notice that the charAt() method takes only one argument which is the position of the specified character in a string.

 

Example of charAt() method to reverse a string in Java

Now we are familiar with the syntax of the charAt() method, let us see how we can use this method to find the reverse of a string. See the example below which prints the reverse of a string using the charAt() method.

// java main class
public class Main {
  // java main method
  public static void main(String[] args) {
    // creating a string  
    String Mystring = "Golinuxcloud";
    // creating empty string for the reverse
    String reversedString = "";
    // for loop to iterate over the string
    for(int i = Mystring.length()-1; i>=0; i--){
      // adding the characters to empty strings, starting from the last character
      reversedString = reversedString + Mystring.charAt(i);
    }
    // printing the reverse of string
    System.out.println("the reverse is: "+reversedString);
  }
}

Output:

Advertisement
the reverse is: duolcxuniloG

Notice that we create a for loop and then we iterated through each character of the string starting from the very last element and added each of the characters one by one to the empty string. If you are not familiar with the for loop, then you can read and learn about it from the article on the java for loop.

 

Method-2: Use getBytes() to reverse a string in Java

The Java String class getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of bytes. We can use the getBytes() method to find the reverse of a string. In this section, we will first look at the basic syntax of getBytes() method and then will solve an example to see how we can find the reverse of string using this method.

 

Syntax of getBytes() method

As we already discussed that the getBytes() method will split or convert the given string into bytes. The temporary byte array length will be equal to the length of the given string. It can be implemented in various ways. The two most common ways as follows:

public byte[] getBytes(String charsetName);

The above method is used to encodes the Strings into a sequence of bytes using the specified charset and return the array of those bytes. The second way could be as follows:

public byte[] getBytes();

This method actually encodes the String using the default charset method. In our program, we will use the following syntax to call the getBytes() method for the reversal of string.

byte[] array = stringNAme.getBytes();

Here we are actually creating a new array typed of bytes and calling the getBytes() method.

 

Example of getBytes() method to reverse a string in Java

Now we are familiar with getBytes() method and how to use it in our program. In this section, we will see how we can use this method to find the reverse of a string. See the example below:

// java main class
public class Main{
  // java main method
  public static void main(String[] args) {
    // creating string
    String string = "Golinuxcloud";
    // calling the getByte() method
    byte[] ByteArray = string.getBytes();
    // creating array to contain the reverse of string
    byte[] reverseArray = new byte[ByteArray.length] ;
    // creating string typed
    String reversedString;
    // using for loop to interate
    for(int i = 0;  i<=ByteArray.length-1; i++) {
      // accessing the elements of reversed array
      reverseArray [i] = ByteArray[ByteArray.length-i-1];
    }
    // creating new string object
    reversedString = new String(reverseArray);
    // printing the reverse
    System.out.print("The reversed string is: "+reversedString);
  }
}

Output:

Advertisement
The reversed string is: duolcxuniloG

In the program above, we first call the getBytes() method and stored the elements in an array of bytes, and then access the elements in reverse order and stored them in another array. Finally, we convert the reversed array of elements into a string and print it.

 

Method-3: Use toCharArray() to reverse a string in Java

The toCharArray() method converts a string to a char array in Java. This method lets you manipulate individual characters in a string as list items. In simple words, toCharArray() is a built-in Java method that is used to convert a string to an array of characters. In this section, we will see the basic syntax of this method and will learn how we can use the toCharArray() method to reverse a string in Java.

 

Syntax of toCharArray() method

As we discussed, the toCharArray() method lets us manipulate individual characters in a string as an array of elements. Spaces, numbers, letters, and other characters are all added to the char array. The basic syntax looks like this:

char[] arrayName = stringName.toCharArray();

The char[] declares an array of chars followed by the name of the array. Then on the right side, we call the toCharArray() method with the name of the string that we want to convert into an array.

 

Example of toCharArray() to reverse a string in Java

Now let us take an example and see how we can use the toCharArray() method to reverse a string in Java. First, we will convert our string into an array, then by using for loop, we will iterate through the array and store the elements in another empty string in reverse order. See the example below:

// Java main class
public class Main {
  // java main method
  public static void main(String[] args) {
    // creating string type
    String string = "Golinuxcloud";
    // calling toCharArray() method
    char [] stringArray = string.toCharArray();
    // creating an empty string
    String reversedString = "";
    // using for loop
    for(int i = stringArray.length-1; i>=0; i--) {
      // stroing the elements in a empty string in reverse order
      reversedString = reversedString + stringArray[i];
    }
    // printing the reverse a string in java
    System.out.println("The reverse is : "+ reversedString);
  }
}

Output:

The reverse is : duolcxuniloG

Notice that we had successfully reversed the given string using the toCharArray() method.

 

Method-4: Use Reverse() to reverse a string in Java

The reverse() method is an inbuilt method that is used to reverse the characters in the StringBuffer. The method causes this character sequence to be replaced by the reverse of the sequence. In this section, we will learn the basic syntax of the reverse() method and then will solve an example of reversing a string using this method.

 

Syntax of reverse() method

Now let us see the basic syntax of reverse() method to reverse a string in java. First, we have to create a StringBuffer object and provide the string, then we can apply the reverse method on StringBuffer. See the syntax below:

StringBuffer stringName = new StringBuffer(string);
stringName.reverse();

Notice that we created a StringBuffer object first and then applied the reverse method on it, which returns the reverse of the string.

 

Example of the reverse() method to reverse a string in Java

Let us now take an example and see how we can apply the reverse() method to find the reverse of a string in Java. See the example below:

// java main class
public class Main{
  // java main method
  public static void main(String args[]){
    // creating string
      String string = "Golinuxcloud";
      // creating StringBuffer
      StringBuffer reverseString = new StringBuffer(string);        
      // reverses the string buffer
      reverseString.reverse();
      System.out.println("The reversed is :" + reverseString);
  }
}

Output:

The reversed is :duolcxuniloG

Notice that we successfully reversed the string using the reverse method.

 

Summary

We know that reversing a string is the technique that reverses or changes the order of a given string so that the last character of the string becomes the first character of the string and so on. In this tutorial, we covered four different methods to reverse a string in java, including  charAt(), getBytes(), toCharArray() and reverse() method. We first, learned the basic syntax of these methods and then solved various examples of reversing strings. In a nutshell, this tutorial contains the popular and simple ways to reverse a string in java.

 

Further Reading

Strings class in java 
toCharArray() method in java
StringBuffer in java 

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment