Reverse String in Java
Reverse a given string using a loop.
BeginnerModule 4: String ProgramsExample 1 of 25
reverse-string.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter a string: ");7 String s = sc.nextLine();89 String rev = "";10 for (int i = s.length() - 1; i >= 0; i--) {11 rev += s.charAt(i);12 }1314 System.out.println("Reversed string: " + rev);15 sc.close();16 }17}
Output
Enter a string: hello Reversed string: olleh
What's going on
We iterate from the last character to the first, building a new reversed string.