How to reverse a string in Java

Using CharAt() method

The CharAt() method is a built-in method that returns the character at the specified index in the given String.

The syntax is

public char charAt(int index)

Let us consider a String initial = "Java Programming Language". The example below illustrates how to reverse the string using ChartAt() method.

import java.util.*;
public class StringReverse {
  public static void main(String args[]) {
    String initial, rev = "";
    initial = "Java Programming Language";
    System.out.println("Original String: " + initial);
    int length = initial.length(); // getting length of array
    for (int i = length - 1; i >= 0; i--) // i-- iterates from last position to first
      rev = rev + initial.charAt(i); // charAt(i) returns the character position at i
    System.out.println("Reversed String: " + rev);
  }
}

The output is

Original String: Java Programming Language
Reversed String: egaugnaL gnimmargorP avaJ

Using toCharArray() method

The toCharArray() method is a built-in method in Java String Class that converts a given string to a character array.

Let us take string str = " Personal Computer". In the example below toCharArray() method converts the string str to a character array, the array iterated in reverse order.

import java.io.*;
import java.util.*;
public class ReverseString {
  public static void main(String[] args) {
    String str = "Personal Computer";
    System.out.println("Original String: ");
    System.out.print(str);
    // convert String to character array by using toCharArray
    char[] arry = str.toCharArray();
    System.out.println("\n");
    System.out.println("Reversed String: ");
    for (int i = arry.length - 1; i >= 0; i--)
      System.out.print(arry[i]);
  }
}

The output is

Original String: 
Personal Computer

Reversed String: 
retupmoC lanosreP

Using Recursion

Recursion in Java is a process in which a method calls itself continuously. The recursion function first removes the first character from the string and appends that character at the end of the string. It repeats the above step until the input string becomes empty.

Let us take a string result = "Java Tutorial". The example below illustrates how to reverse a string using the recursion function.

public class StringReverse {
  // recursion function to reverse string
  public String reverseString(String str) {
    if (str.isEmpty()) {
      return str;
    } else {
      return reverseString(str.substring(1)) + str.charAt(0);
    }
  }
  public static void main(String[] args) {
    StringReverse obj = new StringReverse();
    String result = obj.reverseString("Java Tutorial");
    System.out.println("Original String: Java Tutorial");
    System.out.println("Reversed String: " + result);
  }
}

The output is

Original String: Java Tutorial
Reversed String: lairotuT avaJ

Using String Buffer/String Builder Class

String class does not have a reverse() method, we need to convert the input string to StringBuffer or StringBuilder. The StringBuffer and StringBuilder Class have a built-in method reverse() that returns the reverse of a given string.

Let's take a string strbfr = "Programmer". In the example, the reverse() method returns the reverse of the strbfr.

import java.io.*;
import java.util.*;
public class Buffercls {
  public static void main(String[] args) {
    String strbfr = "Programmer";
    System.out.println("Original String: " + strbfr);
    // conversion from String object to StringBuffer
    StringBuffer sbr = new StringBuffer(strbfr);
    // StringBuilder sbr = new StringBuilder(strbfr) can also be used for conversion
    // To reverse the string
    sbr.reverse();
    System.out.println("Reversed String: " + sbr);
  }
}

The output is

Original String: Programmer
Reversed String: remmargorP

Using getBytes() method

The getBytes() method is a built-in method in Java that is used to convert the input string into a bytes array.

Let us consider a String byt = " Marvellous". Example below illustrates how to use getBytes() method to reverse byt.

import java.io.*;
import java.util.*;
public class ReverseString {
  public static void main(String[] args) {
    String byt = " Marvellous";
    System.out.println("Original String: " + byt);
    // getBytes() method to convert string into bytes[].
    byte[] ByteArray = byt.getBytes();
    byte[] result = new byte[ByteArray.length];
    // Store result in reverse order into the result byte[]
    for (int i = 0; i < ByteArray.length; i++)
      result[i] = ByteArray[ByteArray.length - i - 1];
    System.out.println("Reversed String: " + new String(result));
  }
}

The output is

Original String:  Marvellous
Reversed String: suollevraM 

To reverse the string without changing the word's position

By using split(), charAt() and for loop, we can reverse the string without changing the position of the word in the sentence.

For example, if the string input = "Practice makes man perfect", then the output will be "ecitcarP sekam name tcefrep".

In the example program below, the string is first split into substrings using split() method. The substrings are stored in a String array res. The program then reverses each word of the substring using a reverse for loop.

public class Example {
  public void reverseWordInMyString(String str) {
    String[] res = str.split(" "); //splitting array into substrings
    String reversedString = "";
    for (int i = 0; i < res.length; i++) {
      String word = res[i];
      String reverseWord = "";
      for (int j = word.length() - 1; j >= 0; j--) {
        reverseWord = reverseWord + word.charAt(j); //The charAt() function returns 
        //the character at the given position in a string
      }
      reversedString = reversedString + reverseWord + " ";
    }
    System.out.println(str);
    System.out.println(reversedString);
  }
  public static void main(String[] args) {
    Example obj = new Example();
    obj.reverseWordInMyString("Practice makes man perfect");
  }
}

The output is

Practice makes man perfect
ecitcarP sekam nam tcefrep 

To reverse the words of a given string

In this method, we will reverse the position of the words from last to first without actually reversing the string of each word.

For example, if the string is s = "I love Programming", then the output will be "Programming love I".

Initially, we will reverse the individual words of the given string one by one. For the above example, after reversing individual words the string should be “I evol gnimmargorP”. Then we will reverse the whole string from start to end to get "Programming love I".

The program below illustrates how to reverse the words of a given string

public static void main(String[] args) {
  String input = "I love Programming";
  System.out.println("Original string : " + input);
  String string[] = input.split("\\s");
  String output = "";
  //Reverse each word's position
  for (int i = 0; i < string.length; i++) {
    if (i == string.length - 1)
      output = string[i] + output;
    else
      output = " " + string[i] + output;
  }
  System.out.println("Reversed string : " + output);
}

The output is

Original String: I love Programming 
Reversed String: Programming love I 
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions