
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Reverse a String
Given a String, let's say "str", write a Java program to reverse it. In reverse string operation, we need to display the individual characters of string backwards or from right to left. Here, String is a datatype that contains one or more characters and is enclosed in double quotes(" ").
Let's understand the problem with an example ?
Example Scenario: ?
Input: str = "Java Program"; Output: reversed_string = margorP avaJ
For better understanding refer to the below illustration ?
I | P | S | U | M |
Using Iteration
In this approach, we use the for loop to iterate through each character of the specified string from the beginning to the end. During each iteration, this loop will take the current character and add it to the a new string which will give the final reversed string.
Example
Here is a Java program that shows how to reverse a string using iteration.
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("The reversed string is: "+ reverse_string); } }
Output of the above code is ?
The string is defined as: Java Program The reversed string is: margorP avaJ
Using StringBuilder Class
StringBuilder is a class in Java that represents a mutable sequence of characters. It provides a method called reverse(), which we will use to reverse the characters of given String.
Example
Let's see how to reverse a String using StringBuilder class.
public class ReverseString { public static void main(String[] args) { String input_string= "Tutorialspoint", reverse_string=""; System.out.println("The string is defined as: " + input_string); StringBuilder strBuildObj = new StringBuilder(input_string); // reverse operation reverse_string = strBuildObj.reverse().toString(); System.out.println("The reversed string is: "+ reverse_string); } }
On running the above code, you will get the following result ?
The string is defined as: Tutorialspoint The reversed string is: tniopslairotuT