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
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.
ExampleThe 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:fedcbaUsing 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.
ExampleThe 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
java_strings.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4