0 0
WP Ad Inserter plugin
Read Time:11 Minute, 30 Second

In this article, you can learn 5 simple methods to reverse a string in Java with examples. We have given simple approaches which you can understand easily.

Table of Contents

Example:

You can reverse a string using java with the below approaches. We are given below 5 methods from simplest one to advanced one which you can use to reverse a string according to your requirement.

Approaches to reverse a String:

  1. Reverse a String in Java using for loop
  2. Java program to reverse a String using while loop
  3. Reverse a String in Java using recursion
  4. Java program to reverse a String using a reverse function (StringBuilder Class)
  5. Reverse a String in Java using toCharArray( ) method

Dear reader, let’s go in-depth with each method and learn how to reverse a String. Now, we will learn the first method that is to reverse a String using for loop. 

Read Also: How To Check String Contains Special Characters In Java?

Approach-1: Reverse A String In Java Using For Loop

As String is immutable, so we can’t change a String after we create it. So in this approach, we will reverse a string and store it in another string after reverse. By using for loop, we will iterate through each character of a string and reverse it from the last character to the first character one by one.

Let’s see the Algorithm for the program using for loop and then we will convert this algorithm to a program.

Algorithm to reverse a String in Java:

1. Declare a String str = "Codingface" 2. Display given String. 3. Declare an empty String revStr = " " 4. Iterate String using for loop for(int pos = lastIndex - 1; pos >= 0; pos++) 5. Write logic for reverse string (Reverse String = Reverse String + str.charAt(pos)) 6. Display reversed String
Code language: JavaScript (javascript)

Java program to reverse a String using for loop:

/** * Java program to reverse a String using for loop */ package cf.java.rs; public class ReverseAStringInJava { public static void main(String[] args) { // Declare a String with default value "Codingface" String str = "Codingface"; // Print given String System.out.println("Input String: " + str); // Declare a new empty String to store reversed String String revStr = " "; // For loop to start iteration from last character to first character for (int i = str.length() - 1; i >= 0; i--) { // Use charAt() method to fetch each character of String revStr += str.charAt(i); } // Print String after reverse System.out.println("String after reverse: " + revStr); } }
Code language: JavaScript (javascript)

Output:

Input String: Codingface String after reverse: ecafgnidoC
Code language: JavaScript (javascript)

Explanation of for loop program:

  • In above program, we have taken an example of hard coded string String str = “Codingface“. You can also directly accept any string from user by using Scanner class. To take Scanner class, you can use below piece of code in stead of Line no. 10 of above program:
// Declare a Scanner class Scanner sc = new Scanner(System.in); // Ask user to give any String System.out.println(“Enter any String:”); // Accept String through nextLine() method String name = sc.nextLine();
Code language: JavaScript (javascript)
  • We have used the str.charAt(i) method to retrieve each character of the given String. After getting each character from the last index of the given String,  we will append those characters one by one to the new empty String revStr.

Read Also: How To Find Multiples Of A Float Value In Java?

Approach-2: Reverse A String In Java Using While loop

We can use a while loop to reverse a String through iteration which is just similar to for loop program. While loop will continue till index >= 0 (till the value of the index becomes ‘0’) and then it will be automatically terminated from the loop. We have given below algorithm and program below to understand how you can reverse a String using a while loop.

Let’s see the Algorithm for the program using a while loop and then we will convert this algorithm to a program.

Algorithm to reverse a String using while loop:

1. Declare a String str = "Codingface" 2. Display given String input 3. Declare an empty String revStr = " " 4. Find last index of String using int lastIndex = str.length()-1 5. Use while loop to iterate till index '0' 6. Write logic for reverse the given String input and store it to new String 7. Decrease the value of index by one inside for loop 8. Display reversed String to user
Code language: JavaScript (javascript)

Java program to reverse a String using while loop:

/** * Java program to reverse a String using while loop */ package cf.java.rs; public class ReverseAStringInJavaUsingWhileLoop { public static void main(String[] args) { // Declare a String with default value "Codingface" String str = "Codingface"; // Print given String System.out.println("Input String: " + str); // Declare a new empty String to store reversed String String revStr = " "; // Find last index of the given String int lastIndex = str.length() - 1; // Use a while loop till index 0 while (lastIndex >= 0) { revStr += str.charAt(lastIndex); lastIndex--; } // Print String after reverse System.out.println("String after reverse: " + revStr); } }
Code language: JavaScript (javascript)

Output:

Input String: Codingface String after reverse: ecafgnidoC
Code language: JavaScript (javascript)

Explanation for while loop program:

In the above program, we have declared a String “Codingface“. We found the last index of the given string using the length( ) function(Line no. 13) so that we can use this last index of String to be used as a condition of the while loop

We have used the condition as lastIndex >= 0 with while loop(Line no. 15). It will not be terminated until the value of lastIndex becomes ‘0’. Inside while loop we have used logic to reverse String and then we have decreased the value of lastIndex by one in each iteration. So, the value of lastIndex will be like 10 for the first iteration, then 9, 8,…, 2, 1 & last one 0. Iteration will be transverse from the last index to the first index and the program will append each character to a new String.

Finally, we have displayed the reverse String after the reverse will be done.

Read Also: Java Program To Print Vowels In A String – 2 Simple Programs

Approach-3: Reverse A String In Java Using Recursion

Recursion is the process of calling the same method by itself continuously. We can use recursion in java to reverse a String or to reverse a sentence in Java. In the below program, we use the recursion function which contains logic to reverse String by calling itself continuously. 

Let’s see the Algorithm to reverse a String using recursion and then we will convert this algorithm to a program.

Algorithm to reverse a String using recursion:

1. Declare a String str = "Codingface" 2. Display given String input 3. Declare an empty String revStr = " " 4. Find last index of String using int lastIndex = str.length()-1 5. Use while loop to iterate till index '0' 6. Write logic for reverse the given String input and store it to new String 7. Decrease the value of index by one inside for loop 8. Display reversed String to user
Code language: JavaScript (javascript)

Java program to reverse a String using recursion:

/** * Java program to reverse a String using recursion */ package cf.java.rs; public class ReverseAStringInJavaUsingRecursion { // Declare a method to accept input and reverse String public static String revString(String givenString) { // Check whether given String is empty or not if (givenString.isEmpty() || givenString == " ") { return givenString; } else // Call same function recursively to reverse String return revString(givenString.substring(1)) + givenString.charAt(0); } // Main method public static void main(String[] args) { // Declare a String String str = "Codingface"; // Display given String System.out.println("Given String: " + str); // Reverse given String String revString = revString(str); // Check and Display reversed String if (revString.isEmpty() || revString == " ") System.out.println("Given String is empty!"); else System.out.println("String after reverse: " + revString); } }
Code language: JavaScript (javascript)

Output:

Given String: Codingface String after reverse: ecafgnidoC
Code language: JavaScript (javascript)

Explanation:

In Java programs, execution always starts from the main method. Similarly in the above program, execution will start from the main method and accept String as “Codingface“. Then it will call the revString( ) function with the argument of the given string.

So now, control will go to the revString( ) function(Line no. 6) and check whether a given string is empty or not. If it will be empty, then the revString( ) function simply returns the string, otherwise, it will call the same revString( ) function continuously until it will reverse the given string and finally it will return the reversed string to the main( ) method from where it was called. 

Now, the system will display reversed String to the user after checking whether reversed String is empty or not.

Read Also: 3 Simple Ways To Remove Numbers From String Java

Approach-4: Reverse A String In Java Using reverse( ) function (StringBuilder Class)

String doesn’t provide any predefined reverse( ) method. So we can’t use the reverse( ) function directly to reverse any String input. We can use the predefined reverse( ) function of the StringBuilder class to reverse any String input. To use the reverse( ) function of the StringBuilder class, first can convert the given String input to StringBuilder object, then reverse it by using a reverse( ) function, and finally, convert that reversed StringBuilder object to String. 

Let’s see the Algorithm and then we will convert this algorithm to a program.

Algorithm to reverse a String using reverse( ) function:

Declare a String str = “Codingface” Display given String input Convert String to StringBuilder object Reverse StringBuilder object using reverse() method Convert StringBuilder to String and display reversed String

1. Declare a String str = "Codingface" 2. Display given String input 3. Convert String to StringBuilder object 4. Reverse StringBuilder object using reverse() method 5. Convert StringBuilder to String and display reversed String
Code language: JavaScript (javascript)

Java program to reverse a String using reverse( ) function:

/** * Java program to reverse a String using reverse( ) function */ package cf.java.rs; public class ReverseAStringUsingReverseFunction { public static void main(String[] args) { // Declare a String String str = "Codingface"; // Display given String System.out.println("Given String Input: " + str); // Convert String to StringBuilder StringBuilder sb = new StringBuilder(str); // Reverse StringBuilder using reverse( ) method StringBuilder revSB = sb.reverse(); // Display reversed String System.out.println("String After Reverse: " + revSB.toString()); } }
Code language: JavaScript (javascript)

Output:

Given String Input: Codingface String After Reverse: ecafgnidoC
Code language: JavaScript (javascript)

Read Also: How To Remove Particular Character From String In Java[2021]

Approach-5: Reverse A String In Java Using toCharArray( ) method

We can use the toCharArray( ) method to convert any String to a character array. We can also use this toCharArray( ) method to reverse a String in Java. In this approach, first, we will convert the given String to the character Array and then we can reverse it using for loop as we have already used it in for loop program.

Let’s see the Algorithm and then we will convert this algorithm to a program.

Algorithm to reverse a String using toCharArray( ) function:

1. Declare a String str = "Codingface" 2. Display given String. 3. Convert String to Char Array us toCharArray() method 4. Declare an empty String revStr = " " 5. Iterate String using for loop for(int pos = lastIndex - 1; pos >= 0; pos++) 6. Write logic for reverse string (reversedString = reversedString + charString[pos]) 7. Display reversed String
Code language: JavaScript (javascript)

Java program to reverse a String using toCharArray( ) method:

/** * Java program to reverse a String using toCharArray( ) method */ package cf.java.rs; public class ReverseAStringUsingToCharArrayFunction { public static void main(String[] args) { // Declare a String with default value "Codingface" String str = "Codingface"; // Print given String System.out.println("Given String Input: " + str); // Convert String to Char Array using toCharArray() function char[] charString = str.toCharArray(); // Declare a new empty String to store reversed String String revStr = " "; // Use a for loop to start iteration from last character to first character for (int i = charString.length - 1; i >= 0; i--) { revStr += charString[i]; } // Print String after reverse System.out.println("String After Reverse: " + revStr); } }
Code language: JavaScript (javascript)

Output:

Given String Input: Codingface String After Reverse: ecafgnidoC
Code language: JavaScript (javascript)

Read Also: How to convert Array to XML in Java – 2 easy way

Other readers also ask for:

  1. Write a java program to reverse a string.
  2. How to write a java program to reverse a String.
  3. How do you reverse a string in Java?
  4. How do you reverse a string?
  5. How to write a String reverse program in Java?
  6. Which function is used to reverse a string in Java?
  7. Different types of reversing a string with an explanation.

Java Tutorials.

Source: https://codingface.com/how-to-reverse-a-string-in-java/

Previous post HTML horizontal line
Java Applet Program For Calculator – Do Just In 10 Minutes Next post Java Applet Program For Calculator – Do Just In 10 Minutes

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.