Reverse String
Reverse a given string using a loop.
BeginnerTopic: Module 4: String Programs
Java Reverse String Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String rev = "";
for (int i = s.length() - 1; i >= 0; i--) {
rev += s.charAt(i);
}
System.out.println("Reversed string: " + rev);
sc.close();
}
}Output
Enter a string: hello Reversed string: olleh
Understanding Reverse String
We iterate from the last character to the first, building a new reversed string.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.