w3resource

Java: Reverse a string

Java Basic: Exercise-37 with Solution

Reverse a String

Write a Java program to reverse a string.

Test Data:
Input a string: The quick brown fox

Pictorial Presentation: Reverse a string

Java: Reverse a string

Sample Solution:

Java Code:

import java.util.Scanner;

public class Exercise37 {
    public static void main(String[] args) {
        // Create a scanner to obtain input from the user
        Scanner scanner = new Scanner(System.in);
        
        // Prompt the user to input a string
        System.out.print("Input a string: ");
        
        // Read the input string and convert it to a character array
        char[] letters = scanner.nextLine().toCharArray();
        
        // Display a message before printing the reversed string
        System.out.print("Reverse string: ");
        
        // Iterate through the character array in reverse order and print each character
        for (int i = letters.length - 1; i >= 0; i--) {
            System.out.print(letters[i]);
        }
        
        // Print a newline character to end the output line
        System.out.print("\n");
    }
}

Explanation:

In the exercise above -

  • First, it uses the "Scanner" class to obtain user input.
  • The user is prompted to input a string using System.out.print("Input a string: ").
  • The input string is read using scanner.nextLine() and converted to a character array using toCharArray(). This character array is stored in the 'letters' variable.
  • Next, the code enters a loop that iterates from the last character of the 'letters' array to the first character (in reverse order). Inside the loop, it prints each character, effectively reversing the string character by character.
  • Finally, a newline character is printed to ensure a clean output format.

Sample Output:

Input a string: The quick brown fox                      
Reverse string: xof nworb kciuq ehT

Flowchart:

Flowchart: Java exercises: Reverse a string

Java Code Editor:

Previous: Write a Java program to compute the distance between two points on the surface of earth.
Next: Write a Java program to count the letters, spaces, numbers and other characters of an input string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/basic/java-basic-exercise-37.php