Java: Reverse a word
Reverse Word
Write a Java program to reverse a word.
Pictorial Presentation: Reverse a word

Sample Solution:
Java Code:
import java.util.*;
public class Exercise61 {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner in = new Scanner(System.in);
System.out.print("\nInput a word: ");
// Read a word from the user
String word = in.nextLine();
// Trim any leading or trailing whitespaces
word = word.trim();
// Initialize an empty string for the reversed word
String result = "";
// Convert the word to a character array
char[] ch = word.toCharArray();
// Reverse the word by iterating through the characters
for (int i = ch.length - 1; i >= 0; i--) {
result += ch[i];
}
// Print the reversed word
System.out.println("Reverse word: " + result.trim());
}
}
Sample Output:
Input a word: dsaf Reverse word: fasd
Flowchart:

For more Practice: Solve these Related Problems:
- Write a program to reverse a sentence instead of a single word.
- Modify the program to check if the word is a palindrome.
- Reverse each word in a sentence while keeping word order.
- Implement the program using recursion.
Java Code Editor:
Previous: Write a Java program to find the penultimate (next to last) word of a sentence.
Next: Write a Java program that accepts three integer values and return true if one of them is 20 or more and less than the substractions of others.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics