Reverse a string in Java

Created with Sketch.

 

Reverse a string in Java

Java program to reverse a string that a user inputs. The charAt method is used to get individual characters from the string, and we append them in reverse order. Unfortunately, there is no built-in method in the “String” class for string reversal, but it’s quite easy to create one.

Java program to reverse a string

import java.util.*;

class ReverseString
{
public static void main(String args[])
{
String original, reverse = “”;
Scanner in = new Scanner(System.in);

System.out.println(“Enter a string to reverse”);
original = in.nextLine();

int length = original.length();

for (int i = length 1 ; i >= 0 ; i)
reverse = reverse + original.charAt(i);

System.out.println(“Reverse of the string: “ + reverse);
}
}

 

Output of program:
Reverse string Java program output

Reverse a string in Java using StringBuffer class

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

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

Leave a Reply

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