3 simple ways to reverse String in Java

3 simple ways to reverse String in Java

There are many possible ways to reverse String in Java. We can use a StringBuffer, StringBuilder, and iteration, etc. In this tutorial we will learn writing the Reverse String Program in Java using multiple ways.

1). Using a reverse() method of StringBuilder class

[java]
import java.lang.*;
import java.io.*;
import java.util.*;

class Main
{
public static void main(String[] args)
{
String input = “TutorialWorld”;

StringBuilder str = new StringBuilder();

str.append(input);

str = str.reverse();

System.out.println(str);
}
}
[/java]

Output

2). By Converting String to character array using toCharArray() and then reverse.

Here we will first convert String in to a character array. For this conversion, we have the toCharArray() method. After that iterate this array and print it from last to first order.

[java]
import java.lang.*;
import java.io.*;
import java.util.*;

class Main
{
public static void main(String[] args)
{
String input = “TutorialWorld”;

char[] temp= input.toCharArray();

for (int i = temp.length-1; i>=0; i–)
System.out.print(temp[i]);
}
}
[/java]

Output

3). Using ArrayList object

Using ArrayList which is in Collection Framework in Java. We will first convert the string into the array of character by using toCharArray(). And after the conversion, we will add the characters of the array into the ArrayList object. In Collections, there is a reverse() method that can reverse the array list in one go.

[java]
import java.lang.*;
import java.io.*;
import java.util.*;

class Main
{
public static void main(String[] args)
{
String str = “TutorialWorld”;
char[] chr = str.toCharArray();
List<Character> list1 = new ArrayList<>();

for (char c: chr)
list1.add(c);

Collections.reverse(list1);
ListIterator li = list1.listIterator();
while (li.hasNext())
System.out.print(li.next());
}
}
[/java]

Output