This article will show you how to reverse a string in JAVA. There may be various ways to get to the solution but I am showing 2 easy ways to reverse a string.

Method 1 – This program use charAt method to extract characters from the string and append them in reverse order to reverse the entered string.

class DemoReverseString
{
    public static void main(String args[])
    {
    //Declare varaibles
        String originalString, reverseString = "";
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string to reverse");
    //Store user input into varaible
        originalString = in.nextLine();
    //Take Length of original string
    int length = originalString.length();
    //Loop Through the entire string
    for (int i = length - 1; i >= 0; i--)
            reverseString = reverseString + originalString.charAt(i);
        System.out.println("Reverse of entered string is: " + reverse);
    }
}

Input – JAVA IS EASY TO LEARN

Output – NRAEL OT YSAE SI AVAJ

Method 2 – Reverse string using StringBuffer class

class InvertString
{
    public static void main(String args[])
    {
      StringBuffer a = new StringBuffer("Java programming is fun");
      System.out.println(a.reverse());
    }
}

Input – ALL IS GOOD

Output – DOOG SI LLA

6 thoughts on “Reversing a string

  1. I believe you can even reverse both numbers and string? Just plug in your code and indeed it worked.
    Thanks you so much.

  2. I must say the site is very user friendly and very engaging. I am junior year student in high school and I must say this is perfect start for any high school student.

Leave a Reply

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