Today we will learn How to Reverse a String in Java Word by Word and also how to reverse a string in java. So before start learning, we will make you know about reversing a string.

What is reversing a String?

Reversing a string means changing the positions of the characters in such a way that the last character comes in the first position, second last on the second position and so on.

For Example the reverse of learnprogramo is omargorpnrael

There are so many ways to reverse a string we will see it one by one.

1. Converting String into Bytes.
2. Using the Inbuilt reverse() Method of StringBuilder Class.
3. By Converting String to Character Array.
4. By Using toCharArray() Method.
5. Using ArrayList Object.
6. Reverse a String word by word.
7. Reverse a String in Java Using Recursion.
8. Reverse a String in Java Using For Loop.
9. Without Using Reverse Function.
10. Using Unicode Right to Left Override.

1. Converting String into Bytes

Converting String into Bytes is one of the java methods to reverse a string. In this program, we will use java inbuilt getBytes() method to convert the given string into the bytes[].

Steps to reverse a string by converting string into bytes:

1st Step: First create a temporary byte[] whose length should be equal to the length of the input string.

2nd Step: Now store the bytes in the reverse order into the byte[].

3rd Step: Finally create the new string the byte[] for storing the result.

So let us see how to write a java program to reverse a string using string into Bytes method.

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

Output:

reverse a string in java

2. Using the Inbuilt Reverse() Method of StringBuilder Class

In java the String Class do not have a reverse() method so we need to convert the given input string into StringBuilder. this method is done using the append method of the StringBuilder.

This method replaces all the character sequences in the reverse order. At last, the characters of the reversed string are printed by scanning from first to the last index.

//Learnprogramo
public class test 
{
public static void main(String[] args) 
{ 
String input = "Learnprogramo";  
StringBuilder input1 = new StringBuilder();   
// append a string into StringBuilder input1 
input1.append(input); 
// reverse StringBuilder input1 
input1 = input1.reverse();   
// print reversed String 
System.out.println(input1); 
} 
} 

Output:

reverse a string in java

3. By Converting String to Character Array

In this program, we will make use of character array for reversing a string. We will use the inbuilt method toCharAt().

Steps to Convert String to Character Array:

1st Step: First read the input String using scanner object scan.nextline() and store that string in the variable str.

2nd Step: Initialize char[]ch.

3rd Step: Here j is the length of the array, and the for loop starts as i>0. Loop prints the character from the index i-1 of array ch.

4th Step: Now print characters from the last index of char array.

//Learnprogramo
import java.util.*;
public class test 
{
public static void main(String[]args)
{
String str;
Scanner scan=new Scanner(System.in);
System.out.print("Enter a string : ");
str=scan.nextLine();	
char[] ch=str.toCharArray(); 
System.out.print("Reverse of a String is :"); 
int j=ch.length;
for(int i=j;i>0;i--)
{
System.out.print(ch[i-1]); 
}
}
} 

Output:

how to reverse a string in java

4. Using toCharArray() Method

In this program, we are going to use another inbuilt method called toCharArray(). In this method, we first scan the character array from both the sides i.e from the start and the last index simultaneously.

Step to Use toCharArray() Method:

1st Step: First set the first index to 0 and right index to -1 (length of the string).

2nd Step: Now swap the characters of the start index with the last index one by one.

3rd Step: Increase the left index by 1 using left++ and simultaneously decrease the right index by 1 using right++.

4th Step: Now, Continue till left becomes less than or equal to the right.

//Learnprogramo
public class test 
{
public static void main(String[] args) 
{ 
String input = "learnprogramo"; 
char[] temparray = input.toCharArray(); 
int left, right; 
right = temparray.length-1;   
for (left=0; left < right ; left++ ,right--) 
{ 
// Swap values of left and right 
char temp = temparray[left]; 
temparray[left] = temparray[right]; 
temparray[right]=temp; 
}   
for (char c : temparray) 
System.out.print(c); 
System.out.println(); 
} 
} 

Output:

how to reverse a string in java

5. Using ArrayList Object

In this program, we will use the ArrayList Object for reversing the string. First, we will convert the given string in the character array using java inbuilt method toCharArray(). After converting add all the characters in the ArrayList object. The Collection class reverse() method takes the list object.

For reversing the string we need to pass an ArrayList object which is in the form of a list of the characters.

Steps for Using ArrayList Object:

1st Step: First, copy all the content to the ArrayList Object.

2nd Step: Now create an object using ListIterator() method on ArrayList Object.

3rd Step: ListIterator is used to print the reversed list on the screen.

//Learnprogramo
import java.util.*;
public class test 
{
public static void main(String[] args) 
{ 
String input = "learnprogramo"; 
char[] hello = input.toCharArray(); 
List<Character> programo = new ArrayList<>();   
for (char c: hello) 
programo.add(c);   
Collections.reverse(programo); 
ListIterator li = programo.listIterator(); 
while (li.hasNext()) 
System.out.print(li.next()); 
} 
} 

Output:

using recursion

6. How to Reverse a String Word by Word

In this program, we will accept a string from the user and then print the reversed string on the screen.

Steps to Reverse a String Word by Word:

1st Step: Accept the input string from the user using a scanner object and store the input string in variable str.

2nd Step: Convert the string into char array using the method toCharArray() and then initialize to char[]ch.

3rd step: add ch[0] to the string word if the given block add the characters to the string word until we get the space.

4th Step: If space is found then else block is executed to reverse the word.

5th Step: the 2nd for loop is used to reverse the last word read by the else block.

//Learnprogramo
import java.util.*;
public class test 
{
public static void main(String[ ] arg) 
{
String str;
String word="";
Scanner scan=new Scanner(System.in);
System.out.print("Enter a string : ");
str=scan.nextLine();	 
char[] ch=str.toCharArray(); 
for(int i=0;i<(ch.length);i++)
{
if(ch[i]!=' ')
{
word=word+ch[i];				
}
else
{
for(int c=word.length();c>0;c--)
{
System.out.print(word.charAt(c-1)); 	   
}
System.out.print(" "); 	
word="";
} 	   
}
System.out.println("Reverse String is=");
for(int c=word.length();c>0;c--)
{    
System.out.print(word.charAt(c-1)); 	   
}
}
}

Output:

using for loop

7. Reverse a String in Java Using Recursion

Recursion is nothing but the function calls itself directly or indirectly. In this program, we will write a recursive method to reverse the string.

Steps to Reverse a String in Java Using Recursion:

1st Step: Create an object Using a Class StringRecursion r.

2nd Step: Now read the String using Scanner class and store it in variable s.

3rd Step: We have called the reverse method r.rev(s) and the reverse of the string is done.

4th Step: Now the Reverse String is Printed.

//Learnprogramo
import java.util.*;
public class test 
{
String rev(String str) {
if(str.length() == 0)
return " ";
return str.charAt(str.length()-1) + rev(str.substring(0,str.length()-1)); }
public static void main(String[ ] args) 
{
test r=new test();
Scanner sc=new Scanner(System.in);
System.out.print("Enter the string : ");
String s=sc.nextLine();
System.out.println("Reversed String: "+r.rev(s)); }
}

Output:

using while loop

8. Reverse a String in Java Using For Loop

In this program, we will use for loop to reverse a string in java. The for loop in program iterates from j=length of the string to j>0. Now it prints the character of the string from the index (i-1) and the reverse string is printed on the screen.

import java.util.*;
public class test 
{
public static void main(String[ ] arg)
{
String str;
char ch;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string : ");
str=sc.nextLine();	
System.out.println("Reverse of a String '"+str+"' is  :"); 
for(int j=str.length();j>0;--j)
{
System.out.print(str.charAt(j-1)); 
}
}
}

Output:

using functions

9. How to Reverse a String in Java Without Using Reverse Function

Now we will write a program to reverse a String in java without using a reverse function using while loop.

This while loop executes until the condition i>0 becomes false.

import java.util.*;
public class test 
{
public static void main(String[ ] arg)
{
String str;
Scanner scan=new Scanner(System.in);
System.out.print("Enter a string : ");
str=scan.nextLine();	
System.out.println("Reverse of a String '"+str+"' is  :"); 
int i=str.length();
while(i>0)
{
System.out.print(str.charAt(i-1)); 
i--;
}
}
}

Output:

reverse a string in java

10. Using Unicode Right to Left Override

In this program, we will use Unicode Right to Left Override Method to Reverse a String in java. Let us see how the program is written with output.

//Learnprogramo
import java.util.*;
public class test 
{
// Function to reverse a string in Java by Unicode
// Right-to-left Override (RLO) character
public static String reverse(String str)
{
return "\u202E" + str;
}
public static void main (String[] args)
{
String str = "Learnprogramo";
// string is immutable
str = reverse(str);
System.out.println("Reverse of the given string is : " + str);
}
}

Output:

using different method in java

Conclusion:

we have discussed all the java methods to reverse a string. Hope you understand all the methods and if you have any doubt then please feel free to mention in the below comment box.

Also Read: