- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Reverse a String in Java
Reversing a string is a common operation that can be done in multiple ways. Java provides both built-in methods and manual approaches to reverse a string. We can reverse a string using StringBuffer, StringBuilder, iteration, etc. The following are the approaches for reversing a string
Using StringBuffer class to reverse a strings
Using toCharArray() and a for loop
Using StringBuffer class to reverse a strings
StringBuffer class is used to create strings that can be changed. Unlike the String class, which is unchangeable, StringBuffer lets you modify the string without making a new object each time.
Example
The following example shows how to reverse a String after taking it from the command line argument. The program buffers the input String using the StringBuffer(String string) method, reverses the buffer, and then converts the buffer into a String with the help of the toString() method
public class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
Output
String before reverse:abcdef String after reverse:fedcba
Using toCharArray() and a for loop
The toCharArray() method is used to convert a string into an array of characters. This allows you to access and manipulate each character individually.
Example
The following is an example of reversing a string by using toCharArray() method
import java.io.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
String input = "tutorialspoint";
char[] try1 = input.toCharArray();
for (int i = try1.length-1;i >= 0; i--) System.out.print(try1[i]);
}
}
Output
tniopslairotut