In this article, we will understand how to reverse a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”). Reverse string is displaying the string backwards or from right to left.
Below is a demonstration of the same −
Suppose our input is −
The string is defined as: Java Program
The desired output would be −
The reversed string is: margorP avaJ
Algorithm
Step 1 - START Step 2 - Declare two string values namely input_string and reverse_string, and a char value namely temp. Step 3 - Define the values. Step 4 - Iterating using a for-loop, assign the i’th character to temp and later assign the ‘temp + reverse_string’ to reverse_string value. I.e adding the first element of the string to the last position of the reverse_string. Store the value. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class ReverseString { public static void main (String[] args) { String input_string= "Java Program", reverse_string=""; char temp; System.out.println("The string is defined as: " + input_string); for (int i=0; i<input_string.length(); i++) { temp= input_string.charAt(i); reverse_string= temp+reverse_string; } System.out.println("\nThe reversed string is: "+ reverse_string); } }
Output
The string is defined as: Java Program The reversed string is: margorP avaJ
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class ReverseString { static void reverse(String input_string){ String reverse_string = ""; char temp; for (int i=0; i<input_string.length(); i++) { temp= input_string.charAt(i); reverse_string= temp+reverse_string; } System.out.println("\nThe reversed string is: "+ reverse_string); } public static void main (String[] args) { String input_string= "Java Program"; System.out.println("The string is defined as: " + input_string); reverse(input_string); } }
Output
The string is defined as: Java Program The reversed string is: margorP avaJ