1) Reverse string without using StringBuffer.reverse() method
Here, we will reverse the string without using StringBuffer.reverse() method, consider the given program:
import java.util.*;
class ReverseString
{
public static void main(String args[])
{
//declaring string objects
String str="",revStr="";
Scanner in = new Scanner(System.in);
//input string
System.out.print("Enter a string :");
str= in.nextLine();
//get length of the input string
int len= str.length();
//code to reverse string
for ( int i = len- 1 ; i >= 0 ; i-- )
revStr= revStr+ str.charAt(i);
//print reversed string
System.out.println("Reverse String is: "+revStr);
}
}
Output
Enter a string :Hello World!
Reverse String is: !dlroW olleH
2) Reverse string with using StringBuffer.reverse() method
Here, we will reverse the string using StringBuffer.reverse() method, consider the given program:
import java.util.*;
public class ReverseString
{
public static void main(String args[])
{
//declare string object and assign string
StringBuffer str= new StringBuffer("Hello World!");
//reverse the string
str.reverse();
//print the reversed string
System.out.println("String after reversing:" + str);
}
}
1) Reverse string without using StringBuffer.reverse() method
Here, we will reverse the string without using StringBuffer.reverse() method, consider the given program:
Output
2) Reverse string with using StringBuffer.reverse() method
Here, we will reverse the string using StringBuffer.reverse() method, consider the given program:
Output