In this post of Reverse a string in Java program with 6 Different Ways We will learn how to reverse a String in java using in-built API and own custom logic.
There are several ways to solve the programming problem. Library classes may be very useful in solving programming problems. If you do not know these classes and methods, then you will spend time in writing your own methods and wasting time.
We will use the programming problem to return a reverse of the given string in various ways in this post.
If you run any of the client program that will ask you to enter string which you want to reverse as below:
1 2 3 |
Enter string which you want to reverse:: JavaTutorials Reversed String:slairotuTavaJ |
I have tested these programs for input string “JavaTutorials” and I got Reversed String: “slairotuTavaJ” output.
You can test these programs for various input string.
Approach 1:
This approach using non-recursive solution. It follows the logic of starting from the end of the String and keep moving back character by character and keep appending those characters to form a new string which is reverse of the given input String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Java program to Reverse a String */ public class ReverseStringTest1 { public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in)) { //Taking input from keyboard using Scanner System.out.println("Enter string which you want to reverse::"); String inputText = scanner.next(); String reversedString = reverseStringUsingForwardLogic(inputText); System.out.println("Reversed String:" + reversedString); } catch (Exception e) { System.out.println(e.getMessage()); } } private static String reverseStringUsingForwardLogic(String inputText) { // base case if input is null or empty if (inputText == null || inputText.trim().isEmpty()) return inputText; String reverse = ""; for (int i = inputText.length()-1; i>=0 ; i--) { char c = inputText.charAt(i); reverse = reverse+c; } return reverse; } } |
Approach 2:
This approach also using non-recursive solution Here first of all we converted input string into character array using toCharArray() method of String class. After that It follows the logic of starting from the end of the character array and keep moving back character by character and keep appending those characters to form a new string which is reverse of the given input String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Java program to Reverse a String */ public class ReverseStringTest2 { public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in)) { //Taking input from keyboard using Scanner System.out.println("Enter string which you want to reverse::"); String inputText = scanner.next(); String reversedString = reverseStringUsingForwardLogic(inputText); System.out.println("Reversed String:" + reversedString); } catch (Exception e) { System.out.println(e.getMessage()); } } private static String reverseStringUsingForwardLogic(String inputText) { // base case if input is null or empty if (inputText == null || inputText.trim().isEmpty()) return inputText; String reverse = ""; //Convert string into character array char[] charArray = inputText.toCharArray(); for (int i = inputText.length()-1; i>=0 ; i--) { reverse +=charArray[i]; } return reverse; } } |
Approach 3:
This approach can be described as below steps:
Step 1. First of all convert input string into array of bytes as below
byte[] bytes = inputText.getBytes();
Step 2. Create a temporary byte [] array of length equal to length of the input string or length of bytes array(step1).
byte []revByteArr = new byte[bytes.length];
Step 3. Store the bytes (from step1) in reverse order into temporary byte []revByteArr array which we created in step 2
Step 3. Finally create a new String Object with byte revByteArr[] to store the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Java program to Reverse a String */ public class ReverseStringTest3 { public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in)) { //Taking input from keyboard using Scanner System.out.println("Enter string which you want to reverse::"); String inputText = scanner.next(); String reversedString = reverseStringUsingForwardLogic(inputText); System.out.println("Reversed String:" + reversedString); } catch (Exception e) { System.out.println(e.getMessage()); } } private static String reverseStringUsingForwardLogic(String inputText) { // base case if input is null or empty if (inputText == null || inputText.trim().isEmpty()) return inputText; //Convert string into byte array byte[] bytes = inputText.getBytes(); byte []revByteArr = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { revByteArr[i] = bytes[bytes.length-i-1]; } String reverseString = new String(revByteArr); return reverseString; } } |
Approach 4:
In this approach first of all Convert the input string into character array by using the toCharArray() of String class after that scan the character array from both sides Like from the starting index (left) as well as from last index(right) simultaneously.
- First set the left index equal to 0 and right index equal to the length of the string -1.
- Now swap the characters of the start index scanned with the last index scanned one by one. Afterwards that, increase the left index by 1 (left++) and you to decrease the right by 1 i.e. (right–) to move on to the next characters in the character array.
- This process has to continue till left index is less than or equal to the right index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Java program to Reverse a String */ public class ReverseStringTest4 { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { //Taking input from keyboard using Scanner System.out.println("Enter string which you want to reverse::"); String inputText = scanner.next(); String reversedString = reverseStringUsingForwardLogic(inputText); System.out.println("Reversed String:" + reversedString); } catch (Exception e) { System.out.println(e.getMessage()); } } private static String reverseStringUsingForwardLogic(String inputText) { // base case if input is null or empty if (inputText == null || inputText.trim().isEmpty()) return inputText; //Convert string into character array char[] inputByteArray = inputText.toCharArray(); int left, right = inputByteArray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right index char temp = inputByteArray[left]; inputByteArray[left] = inputByteArray[right]; inputByteArray[right] = temp; } String reverseString = new String(inputByteArray); return reverseString.toString(); } } |
Approach 5:
In this approach we have passed input string to StringBuffer constructor in that way we have converted input string into StringBuffer and finally we have called reverse() method of StringBuffer class.
If you are not concern about thread safety then you may use StringBuilder(this class also has reverse() method) instead of StringBuffer class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Java program to Reverse a String */ public class ReverseStringTest5 { public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in)) { //Taking input from keyboard using Scanner System.out.println("Enter string which you want to reverse::"); String inputText = scanner.next(); String reversedString = reverseStringUsingBuffer(inputText); System.out.println("Reversed String:" + reversedString); } catch (Exception e) { System.out.println(e.getMessage()); } } private static String reverseStringUsingBuffer(String inputText) { // base case if input is null or empty if (inputText == null || inputText.trim().isEmpty()) return inputText; //Making use of StringBuffer reverse() method StringBuffer sb = new StringBuffer(inputText); sb.reverse(); return sb.toString(); } } |
Approach 6:
In this approach we will create a function to reverse a string input taken by user and later we will call it recursively until all characters are reversed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Java program to Reverse a String using recursion */ public class ReverseStringTest6 { public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in)) { //Taking input from keyboard using Scanner System.out.println("Enter string which you want to reverse::"); String inputText = scanner.next(); String reversedString = reverseString(inputText); System.out.println("Reversed String:" + reversedString); } catch (Exception e) { System.out.println(e.getMessage()); } } private static String reverseString(String inputText) { // base case if input is null or empty if (inputText == null || inputText.trim().isEmpty()) return inputText; //Calling Function Recursively return reverseString(inputText.substring(1)) + inputText.charAt(0); } } |
Would you like to watch on YouTube:
Reverse a string in Java program
That’s all about how to reverse a string in Java.
You May Also Like:
Splitting a String in Java using a delimiter
Count number of words in a string java
Count total number of times each character appears in the string in java
Check if two strings are anagrams or not in java
How to convert string to int without using library functions in java
Check Whether a Given String/Number is a Palindrome in java
How to find first non-repeated character in a given String in Java
How to find first non-repeatable character from a String using Java 8
Java Program to find the frequency of each character in String ?
If you have any feedback or suggestion please feel free to drop in blow comment box.