Java program to reverse a String

How to reverse a given string in java?

There are two way to way to reverse a given String.

  1. Using reverse() method of StringBuffer class
  2. Using charAt() method

Example

package com.anil.test;

public class ReverseString {
	public String reverseMyString(String str){		
		StringBuffer buffer = new StringBuffer(str);
		buffer.reverse();
		return buffer.toString();
	}
	public String reverseMyStringWithoutBuffer(String str){
		int length = str.length();
		String original = str;
		String reverse = "";
		for(int i = length-1; i>=0; i--){
			reverse = reverse + original.charAt(i);			
		}		
		return reverse;
	}
	public static void main(String[] args){	
		
		ReverseString rs = new ReverseString();
		System.out.println("Reversed String using Buffer: "
                          +rs.reverseMyString("Hello world"));
		System.out.println("Reversed String without Buffer: 
                         "+rs.reverseMyStringWithoutBuffer("Hello world"));
	}

}

Output:

Reversed String using Buffer: dlrow olleH
Reversed String without Buffer: dlrow olleH

Comments

  1. By om anand giri

    Reply

    • By anil

      Reply

  2. By Mrityunjay

    Reply

    • By anil

      Reply

  3. Reply

  4. Reply

  5. Reply

  6. By Sangita Kumari

    Reply

  7. By satish

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


four − 2 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>