Objective

One of the most used examples in schools in learning java programming is to find solutions on how to reverse an array in java. This will be a little bit tricky however if you find the right API in java, it would be very easy. The example below will let us learn on how to use Scanner to get the user input. And also we would learning as well on how to use the reverse method of StringBuffer class.

Reverse a String in Java Example

This java example source code shows how to reverse a string using the reverse method of StringBuffer. Basically we ask for a user string and then we reverse it using the reverse() method of StringBuffer Class.

package com.javatutorialhq.java.examples;

import static java.lang.System.*;

import java.util.Scanner;

/*
 * This basic java example source code
 * shows how to reverse a String
 */

public class DeleteSingleCharExample {

	public static void main(String[] args) {
		// Ask for user input
		out.print("Enter a string to reverse:");
		// get the user input using scanner
		Scanner scan = new Scanner(System.in);
		String originalString = scan.nextLine();
		// reverse the original string
		String newString = new StringBuffer(originalString).reverse().toString();
		// print the string in reverse order
		out.println("String in reverse Order:"+newString);
		// close the scanner object
		scan.close();

	}

} 

Sample Output

Running the above java source code will give the following output:

Enter a string to reverse:123456789
String in reverse Order:987654321

 Suggested Reading List