w3resource

Java: Reverse a word


Reverse Word

Write a Java program to reverse a word.

Pictorial Presentation: Reverse a word

Java Basic Exercises: 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:

Flowchart: Java exercises: Reverse a word


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.

Go to:


PREV : Find Penultimate Word.
NEXT : Check Subtraction Difference.


Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.