w3resource

Java: Reverse a word

Java Basic: Exercise-61 with Solution

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

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.



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-61.php