In Java, to find a reverse of a string is a common task. We can reverse a string with various methods available, such as using loops like while and for, or using StringBuilder for efficiency. For instance, reversing the String “hi” results in “ih”.
In this article we will learn how to find reverse of a String through example, detailed logic and program explanation for better understanding.
Required Knowledge
- Java programming basics
- Java operators
- StringBuilder
- Loop concepts
Problem Statement
We have to write a java program to find the reverse of a string. The program will take input string and should output reverse of the string. This action will be done in our program. Let’s see an example,
Example:
For a given input String str “Learn java through Interview Expert”, Output should be ” trepxE weivretnI hguorht avaj nraeL”.
Explanation:
Input String str: "Learn java through Interview Expert"
The reversed string should start from the last word and each word should be reversed individually.
Reverse of str: trepxE weivretnI hguorht avaj nraeL
Hence, we have the reverse of the string (str).
Logic to find reverse of a string
There are multiple logics to find a reverse of a string in java programming language.
Logic 1: Using StringBuilder
- Take input from string (str) from the user.
- Create a StringBuilder object s initialized with the contents of str. The StringBuilder class is used because it provides a convenient method reverse() to reverse the sequence of characters in the string.
- After reversing, using print statement display the reversed string.
Logic 2: Using while loop
- Take input string (str) from the user.
- Convert the string str into a character array ch.
- Initialize an empty string revStr to store the reversed string.
- Initialize an integer i to the index of the last character in ch.
- Using a while loop, iterate from the last character to the first character (i from ch.length-1 to 0).
- Inside the loop, append each character from ch to the string revStr in reverse order.
- After loop completes, print the string revStr, which now contains the reversed version of the input string str.
Logic 3: Using for loop
- Take user input for a text string (str).
- Initialize an empty string outputRev to store the reversed string.
- Use a for loop to iterate backwards through the characters of str starting from the last character (str.length()-1) down to the first (0).
- Inside the loop, append each character (str.charAt(i)) to the outputRev string.
- After the loop completes, outputRev contains the reversed string.
- Print outputRev to display the reversed string to the user.
Java program to find the reverse of a string
Program 1: Using StringBuilder
In the below program we are using StringBuilder to find the reverse of a string.
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a text");
String str = sc.nextLine();
StringBuilder s = new StringBuilder(str);
s.reverse();
System.out.println("Reverse of a String: "+ s.toString());
sc.close();
}
}
Output:
Please enter a text
Hi, This is a great learning platform
Reverse of a String: mroftalp gninrael taerg a si sihT ,iH
Java program explanation to find the reverse of a string
- The program imports the Scanner class from java.util package to read input from the user.
- It defines a class named
ReverseString
. - Inside the class, there’s a main method, which serves as the entry point of the program.
- In the main method:
- It creates a Scanner object named
sc
to read input from the console. - Asks the user to enter a text and reads the input using
nextLine()
method, storing it in the variable str. - Program creates a StringBuilder object
s
initialized with the content of the str. - It calls the
reverse()
method on the StringBuilder objects
to reverse the characters. - It prints the reversed string using
toString()
method of StringBuilder. - Finally, it closes the Scanner object to release system resources.
- It creates a Scanner object named
Program 2 : Using while loop
In the below program we are using while loop to find the reverse of a string in Java.
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the text :");
String str = s.nextLine();
char ch[]= str.toCharArray();
String revStr="";
int i=ch.length-1;
while(i>=0) {
revStr+=ch[i];
i--;
}
System.out.println(revStr);
s.close();
}
}
Output:
Enter the text :
mroftalp gninrael taerg a si sihT ,iH
Hi, This is a great learning platform
Java program explanation to find the reverse of a string
- The program imports the Scanner class from java.util package to read input from the user.
- It defines a class named
ReverseString
. - Inside the class, there’s a main method, which serves as the entry point of the program.
- In the main method:
- It creates a Scanner object named
s
to read input from the console. - It asks the user to enter a text and reads the input using
nextLine()
method, storing it in the variable str. - Then, it converts the string str into a character array
ch[]
using thetoCharArray()
method. - It initializes an empty string
rev
Str to store the reversed text. - Initializes an integer
i
to the index of the last character in the array. - It enters a while loop that iterates from the last character of the array to the first character.
- Inside the loop, it appends each character of the array in reverse order to the
rev
Str string. - After the loop completes, it prints the
rev
Str string, which contains the reversed text. - Finally, it closes the Scanner object to release system resources.
- It creates a Scanner object named
Program 3: Using for loop
In the below program we are using while loop to find the reverse of a string.
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the text :");
String str = s.nextLine();
String outputRev="";
for(int i=str.length()-1;i>=0;i--) {
outputRev+=str.charAt(i);
}
System.out.println(outputRev);
s.close();
}
}
Output:
Enter the text :
I Love Interview Expert Website
etisbeW trepxE weivretnI evoL I
Java program explanation to find the reverse of a string
- The program imports the Scanner class from java.util package to read input from the user.
- It defines a class named
ReverseString
. - Inside the class, there’s a main method, which serves as the entry point of the program.
- In the main method:
- It creates a Scanner object named
s
to read input from the console. - Asks the user to enter a text and reads the input using
nextLine()
method, storing it in the variable str. - It initializes an empty string
outputRev
to store the reversed text. - It enters a for loop that iterates over each character of the string text in reverse order.
- Inside the loop, it appends each character of the string in reverse order to the
outputRev
string. - After the loop completes, it prints the
outputRev
string, which contains the reversed text. - Finally, it closes the Scanner object to release system resources.
- It creates a Scanner object named
Conclusion
In this article, we have learnt how to find reverse of a string in Java. We have seen the logic and implemented the program using StringBuilder, while loop and for loop in Java. Hope this article helped you in the understanding of the program.
You can also check our another awesome tutorials:
- Java Program to check whether a string is palindrome or not
- Print maximum among two using switch in Java
- Check if a number is positive or negative or 0 using switch in Java
- Check Armstrong number in Java
Happy Java learning!!