Java Beginner’s Exercise #2 – Java Program to Reverse a String (With Solution)

This is the second exercise in the series of Java Beginner’s Exercises.

In this exercise we will be writing a Java program that will ask the user to input a string. Then reverse and display the string to the user. 

Problem

Write a Java program that will take a string as an input from the user and reverses it. Your string for this exercise is, “I want to change the world”.

Remember, to take the input from the user. Do not assign this string into the program itself. 

Note

Reversing a string is pretty straightforward, even though it might now look like like that. 

For this Java program you should be using the Scanner class for taking an input from the user.

Then, store the length of the string onto a variable. Use the charAt method to get the characters of the string and append them in reverse order using a for loop. 

Sample Solution

import java.util.Scanner;
public class StringReversal{

 public static void main(String[] args){
     String reversed = “”;
     String stringInput;

     Scanner scanner = new Scanner(System.in);

     System.out.print(“Please enter your string: “);
     stringInput = scanner.nextLine();

     for(int i = stringInput.length() – 1; i >= 0; i–){
           reversed = reversed + stringInput.charAt(i);
         }
     System.out.println(“Your reversed string is: “+ reversed);
    }
}

Expected Output

The expected output for this exercise should be dlrow eht egnahc ot tnaw nwI.

Conclusion

This brings us to the conclusion of this second exercise of the Java Beginner’s Exercise series. A Java program to reverse a string. 

You can always try different strings to explore and play around with the code.

Feel free to leave comments. And let me know if you have any questions or concerns. 

Leave a Reply