Java Project - Program to Reverse a String
Reverse a String using a For Loop and Recursion:
Reverse a String:
Input: A string.
Output: The reversed string.
Example:
- Input: "hello"
- Output: "olleh"
- Input: "Java"
- Output: "avaJ"
Solution 1: Reverse a String using a For Loop
Code:
Output:
Enter a string: Java Exercises Reversed string: sesicrexE avaJ
Enter a string: Project Reversed string: tcejorP
Explanation :
- Input: User inputs a string.
- Processing: The program iterates through the string from the last character to the first, appending each character to form a new string.
- Output: The program displays the reversed string.
Solution 2: Reverse a String using Recursion
Code:
Output:
Enter a string: RecursiveReverseString Reversed string: gnirtSesreveRevisruceR
Enter a string: madam Reversed string: madam
Explanation:
- Input: User enters a string.
- Processing: The recursive function processes the string by taking the last character and calling the function again on the rest of the string, building the reversed string step by step.
- Output: The program prints the reversed string.
Java Code Editor: