Reverse a String in Java — Definition, Examples and Program

Learn how to reverse a string in Java using a simple and efficient approach. This blog explains the logic step by step with examples, a Java program, and practice challenges.

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 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:

How the Logic Works

To reverse a string manually:

  1. Start from the last character of the string.
  2. Move towards the first character.
  3. Print or store each character one by one.

Example 1

Input: "CODE"

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

  1. Reverse a string without using an extra variable.
  2. Reverse each word in a sentence separately.
  3. 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.