How to Reverse a String in Java

In this article we will discuss about to Reverse a String in Java with different different examples. Reversing a String in Java is some tricky. Before going ahead we suggest you to look about String vs StringBuilder vs StringBuffer.

Reverse a String in Java

You should know about these concepts:

  • Object of String are immutable
  • String class in Java does not have reverse() method.
  • StringBuilder class has built-in reverse() method.
  • StringBuilder class does not have toCharArray() method.
  • While String class does have toCharArray() method.

1. String Reverse by iterating in Java

In this way first we will iterate over the string and use the Char Data type to hold the character. An another String variable will be used to append the character to the beginning of the string.

2. Using built-in StringBuilder reverse() method.

In this way, we have to convert or store the actual string into the StringBuilder variable, then we can directly reverse the String using the

  • The input word is converted to a StringBuilder object using its constructor, which takes a String.
  • The reverse() method is then called on the StringBuilder object to reverse the string.
  • Finally, the reversed string is obtained by calling toString() on the StringBuilder

3. Using toCharArray() method.

Explanation:

  • It prompts the user to enter a word.
  • It converts the input word into a character array using toCharArray().
  • It initializes a new character array (reversedCharArray) with the same length as the input word.
  • It iterates through the characters of the input word array from the last element to the first, adding each character to the new array.
  • Finally, it constructs a new string from the reversed character array and returns it.

Also see:

Map in Java Full Explanation

Thank you for reaching out us. Please look into more useful tutorials.

Donโ€™t miss new tips!

We donโ€™t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate ยป
Scroll to Top