Java: Reverse a string
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
Sample Solution:
Java Code:
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:
For more Practice: Solve these Related Problems:
- Reverse a string without using built-in functions.
- Modify the program to reverse words instead of characters.
- Reverse only the vowels in a string.
- Implement string reversal using recursion.
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.