Java program to Reverse a String example


Introduction
             Reversing string in java is a simple program but we will come across this program several times, across interviews etc., There are two methods to reverse a string in java.
One is to use the built in string function and other one is to reverse string character by character. Both methods are quite simple now lets go ahead and see the example.

Using Built in function
              Use reverse function of the stringBuffer class to reverse a string as shown below:
StringBuffer original = new StringBuffer("program to reverse string in java");
System.out.println("Reveresed String:: " + original.reverse()); 

Without using built in function
               This method will read the string character by character from reverse in a for loop. This program self exaplanatory..

for (int i = length - 1; i >= 0; i--)
{
  reverse = reverse + original.charAt(i);

}

ReverseString.java

public class JavaReverseString {

    public static void main(String args[]) {
        String original, reverse = "";
        original = "java program to reverse a string";
        int length = original.length();
        for (int i = length - 1; i >= 0; i--) {
            reverse = reverse + original.charAt(i);
        }
        System.out.println("-----------Method 1-------------");
        System.out.println("Original String:: " + original);
        System.out.println("Reveresed String:: " + reverse);
        reverseString();
    }

    public static void reverseString() {
        StringBuffer original = new StringBuffer("program to reverse string in java");
        System.out.println("-----------Method 2-------------");
        System.out.println("Original String:: " + original);
        System.out.println("Reveresed String:: " + original.reverse());
    }


}


Thus we are done with Java program to reverse a string..



Reactions:

1 comment :

  1. import java.io.*;
    class split
    {
    public static void main(String args[])throws IOException
    {
    String str[];
    String finalstr="";
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    str=br.readLine().split(" ");
    for(int i=str.length-1;i>=0;i--)
    finalstr+=str[i]+" ";
    System.out.println(finalstr);
    }
    }

    ReplyDelete