×

Java Programs

Java Practice

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

In this program, there is an example in java where you will learn how to reverse a string with and without using StringBuffer.reverse() method?

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

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

Java String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.