Reverse a String in Java


This Java program uses the StringBuilder class to reverse a given string.

  • The original string is initialized as "Tutor Joes Computer Education"., and it is printed using System.out.println(a).
  • Next, a new StringBuilder object b. is created, and a for loop is used to iterate through the characters of the original string from the end to the beginning (i=a.length()-1;i>=0;i--.).
  • The charAt(). method is used to get each character at the current index, and it is appended to the new StringBuilder object b. using the append(). method.
  • Finally, the reversed string is printed using System.out.println(b) .

Source Code

public class Reverse {
    public static void main(String args[])
    {
        //Program to reverse a given string
        StringBuilder a = new StringBuilder("Tutor Joes Computer Education");
        System.out.println(a);
        StringBuilder b=new StringBuilder();
        for(int i=a.length()-1;i>=0;i--)
        {
            b.append(a.charAt(i));
        }
        System.out.println(b);
    }
}
 

Output

Tutor Joes Computer Education
noitacudE retupmoC seoJ rotuT
To download raw file Click Here

Basic Programs