Hi All,

Greetings of the day!

Today we will see how we can write a program in Java to Reverse a String so let's start.

First, we will initialize a String and convert a String into a character array. Also, we will declare a String variable which will store reverse String as shown below.

  
 	String originalString="abcdefgh";
        char[] chars=originalString.toCharArray();

        String reverseString="";	
  
Now to reverse String we will use a simple for loop which will loop over a character array we declare above. Loop will start from the length-1 position to pick the last character of String first and will continue till the first character of String is picked. And we will add each character to the reverse string variable as shown below.

  
package com.demo.programs;

public class ReverseString {

    public static void main(String[] args) {
        String originalString="abcdefgh";
        char[] chars=originalString.toCharArray();

        String reverseString="";

        for(int i= chars.length-1;i>=0;i--){
            reverseString=reverseString+chars[i];
        }

        System.out.println("Reverse String is "+reverseString);
    }
}
O/P will be 
Reverse String is hgfedcba

Process finished with exit code 0
We need to start picking elements from the character array at the length-1 position instead of character's actual length as in array elements are stored from index 0 so the last element will be at a length-1 position.