Write a Java Program to reverse any String
Java Program to reverse any string in Java Programming, you have to ask to the user to enter the string and start placing the character present at the last index of the original string in the first index of the reverse string (make a variable say reverse to store the reverse of the original string).
SOURCE CODE ::
import java.util.*; public 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 entered string is: "+reverse); } }
OUTPUT ::
Enter a string to reverse CodezClub Reverse of entered string is: bulCzedoC
We can reverse a string using reverse method of StringBuilder class. we will create an object of class StringBuilder and initialize it with input string. Then we call reverse method of StringBuilder class to print reversed string on screen. Here is the full program to reverse a string in Java.