You are here

Java program to reverse a string

Java reverse string program: This Java program reverses a string entered by a user. We use charAt method to extract characters from the input string and append them in reverse order to reverse the string. Unfortunately, there is no built in method in String class for string reversal. Fortunately, it is quiet easy to make a method to do it.

Java programming code to reverse a string

  1. import java.util.*;
  2.  
  3. class ReverseString
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       String original, reverse = "";
  8.       Scanner in = new Scanner(System.in);
  9.      
  10.       System.out.println("Enter a string to reverse");
  11.       original = in.nextLine();
  12.      
  13.       int length = original.length();
  14.      
  15.       for (int i = length - 1 ; i >= 0 ; i--)
  16.          reverse = reverse + original.charAt(i);
  17.          
  18.       System.out.println("Reverse of the string: " + reverse);
  19.    }
  20. }

Download Reverse string program class file.

Output of program:
Reverse string Java program output

Reverse a string in Java using StringBuffer class

  1. class InvertString
  2. {
  3.    public static void main(String args[])
  4.    {
  5.       StringBuffer a = new StringBuffer("Java programming is fun");
  6.       System.out.println(a.reverse());
  7.    }
  8. }

StringBuffer class contains a method reverse which can be used to reverse or invert an object of its class.