Reverse string program in Java

Reverse a string in java Program

The basic idea is to calculate the length of the Input String and then run a Loop construct that extracts character from the Extreme Right till the Extreme Left, i.e from the (N-1)th index to 0th index.

These characters are accumulated in a String Variable that stores the final string. The same is to be printed as result.

Java Code:

/* Program to enter a string and print it after reversing it.*/
import java.util.*;
class ReverseString
public static void main()
Scanner inp=new Scanner(;
System.out.print("\n Enter String: ");
String s=inp.nextLine();
int k=s.length();
int i;
char c;
String z="";

for(i=(k-1);i>=0;i--) { c=s.charAt(i); z=z+c; }

System.out.println("Reversed String: "+z);

} }


Enter String: Brooklyn 99
Reversed String: 99 nylkoorB

Enter String: Riverdale Reversed String: eladreviR

Reverse string program in Java