Java Examples

Java Program - Reverse a given String



In Java, the reverse of a given string can be found out by using below mentioned methods.

Method 1: Using iteration

In the example below, the string called MyString is reversed using ReverseString() method. A variable last is created which points to the last character of the string. An empty string revString is created. By using a for loop and iterating from last to 0, characters from MyString is placed in revMystring in reverse order.

public class MyClass {
  static void ReverseString(String MyString) {
    int last = MyString.length() - 1;

    String revString = "";

    for(int i = last; i >= 0; i--) {
      revString = revString + MyString.charAt(i);
    }

    System.out.println(revString);
  }

  public static void main(String[] args) {
    ReverseString("Hello World");
    ReverseString("Programming is fun");
    ReverseString("Reverse this string");
  }
}

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 2: Using Recursion

The above result can also be achieved using recursive method. Consider the example below:

public class MyClass {
  static void ReverseString(String MyString) {    
    if ((MyString == null) || (MyString.length() <= 1)) {
      System.out.print(MyString);
    } else {
      System.out.print(MyString.charAt(MyString.length()-1));
      ReverseString(MyString.substring(0,(MyString.length()-1)));
    }
  }  

  public static void main(String[] args) {
    ReverseString("Hello World");
    System.out.println();

    ReverseString("Programming is fun");
    System.out.println();
    
    ReverseString("Reverse this string");
    System.out.println();
  }
}

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 3: Printing the string in reverse order

The same can be achieved by printing the string in reverse order. Consider the example below:

public class MyClass {
  static void ReverseString(String MyString) {    
    int last = MyString.length() - 1;

    for(int i = last; i >= 0; i--) {
      System.out.print(MyString.charAt(i));
    }

    System.out.println();
  }  

  public static void main(String[] args) {
    ReverseString("Hello World");
    ReverseString("Programming is fun");
    ReverseString("Reverse this string");
  }
}

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR