This post will discuss various methods to iterate over a string backward in Java.

1. For loop

We can use a simple for-loop to process each character of the string in the reverse direction. This approach is very effective for strings having fewer characters.

Download  Run Code

2. Convert to character array

In this approach, we initially reverse the string. Then we convert the reversed string to a character array by using the String.toCharArray() method. Finally, we iterate the char[] using a for-each loop, as shown below:

Download  Run Code

3. Using CharacterIterator

We can also use the CharacterIterator interface that provides bidirectional iteration for a String.

Download  Run Code

4. Using String.Split() method

String.split() splits the specified string and returns an array of strings created by splitting this string.

Download  Run Code

5. Using Guava Library

Guava’s Lists.charactersOf() returns a view (not a copy) of the specified string as an immutable list of characters. After getting a view, we can process it using an iterator.

The List interface provides a special iterator, called a ListIterator that allows bidirectional access. We can call the List.listIterator(index) method to get a ListIterator over the list elements starting from the specified position in the list.

Download Code

6. Using Reflection

For longer strings, we can inspect any string using reflection and access the backing array of the string. To find the name of the backing array, we can print all the fields of String class using the following code and search one with the type char[].

Download Code

That’s all about iterating over a string backward in Java.

 
Related Post:

Iterate over characters of a String in Java