Reverse a String in Java — Definition, Examples and Program
Reversing a string is one of the most fundamental problems in programming. It helps beginners understand loops, character handling, and string manipulation.
In this blog, we will learn:
- What it means to reverse a string
- Step-by-step examples
- A clean Java program
- Practice challenges
What Does Reversing a String Mean?
Reversing a string means changing the order of its characters so that the last character becomes the first, the second last becomes the second, and so on.
Example:
- "hello" → "olleh"
- "Java" → "avaJ"
- "12345" → "54321"
How the Logic Works
To reverse a string manually:
- Start from the last character of the string.
- Move towards the first character.
- Print or store each character one by one.
Example 1
Input: "CODE"
- Start from index 3 → 'E'
- Index 2 → 'D'
- Index 1 → 'O'
- Index 0 → 'C'
Output: "EDOC"
Java Program to Reverse a String
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed = reversed + input.charAt(i);
}
System.out.println("Reversed String: " + reversed);
}
}
Sample Output
Enter a string: programming
Reversed String: gnimmargorp
Practice Challenges
- Reverse a string without using an extra variable.
- Reverse each word in a sentence separately.
- Check whether a string is a palindrome using the reverse logic.
Reversing a string is a common interview question and a great way to build confidence in string manipulation. Mastering this logic will help you solve many advanced problems easily.