- Java Programming Examples
- 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 Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to reverse a String in Java
Problem Description
How to reverse a String?
Solution
Following example shows how to reverse a String after taking it from command line argument .The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of 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); } }
Result
The above code sample will produce the following result.
String before reverse:abcdef String after reverse:fedcba
Example
Following another example shows how to reverse a String after taking it from command line argument
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]); } }
The above code sample will produce the following result.
tniopslairotut
java_strings.htm
Advertisements