Q:

How to reverse a string in Java with and without using StringBuffer.reverse() method?

belongs to collection: Java String Programs

0

Given a string (Input a string) and we have to reverse input string with and without using StringBuffer.reverse() method in java.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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);
	}  
}

Output

String after reversing:!dlroW olleH

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to check whether a given string is empty or no... >>
<< How to replace string with another string in java ...